您尚未登录,请登录后浏览更多内容! 登录 | 立即注册

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 10544|回复: 0
打印 上一主题 下一主题

[php学习资料] MongoDB高级查询用法大全

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |正序浏览 |阅读模式
版本一:
7 _6 v/ e% f* G. Y) B9 R3 u/ C% ~# K- W6 S4 z# D. D5 }+ L' l
1 ) . 大于,小于,大于或等于,小于或等于/ w" M3 C. p4 l# n% Q6 ~
! q" R; U4 c" S5 y  }
$gt:大于
7 k* x% i1 h1 N! E) {0 H& C$lt:小于5 N9 f7 Y- e" ~- J5 v( g
$gte:大于或等于
+ t; r/ m$ w3 v! G9 ?$lte:小于或等于
+ @3 F% T8 z) c& U
1 e" d, @" N' l例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value; ~. c/ i* E8 t6 B  q
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value, f% X: c! r! J0 _$ l% t0 [
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    * X; Y0 e0 L" d. B& X: s9 v
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
) y, R3 _3 @  W0 B" R) T; p
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});. X2 W7 ]5 R+ O  G/ F$ M2 L; [
  2. db.things.find({j : {$gte: 4}});
复制代码
1 ?# j* f) W# s" B2 @) H& E
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

4 R8 m7 \2 [5 H' Z; G6 i: \* G; Y
& u7 e9 {( c2 @) `
3 r+ S; Y+ q6 f6 r2 p$ Y  s
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
) K& y. b" Y  @; x3 [
3) in 和 not in ($in $nin)! ]) |( |  c. E) r3 W9 U

/ O2 z4 V) m8 Z7 Y语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

/ S2 ?* [( W* |& l! w) i0 g
例子:
  1. db.things.find({j:{$in: [2,4,6]}});/ J1 E: l) k) v' W( Q
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
: G; N. A5 A$ h

) @* n3 k+ R1 m) j0 P9 F4) 取模运算$mod
! e2 }. |/ T2 O# Z; ^. a6 l% a+ {
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
+ u- R, v# c, ^- @
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
5 t7 S& _; L# g: B* c8 h
; A. W/ ^# G9 j1 G! }, J
5)  $all
* {  T! j1 C* H% `8 V) s, o# ~$ N2 X
# P/ f! K! t! X" R# o6 L( ~$all和$in类似,但是他需要匹配条件内所有的值:
  I9 u& F9 p0 T! H+ Q$ x' B
0 v8 t4 @' O3 u* {/ Q7 V如有一个对象:
( h4 {" R$ \7 O4 V+ f
  1. { a: [ 1, 2, 3 ] }
复制代码
9 p$ ]- G3 b& ?! k, u
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
1 Y; t4 c; I) [" i
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
% @4 Z/ a8 _1 \, q* c, v
4 i" `6 v% u( P0 d4 c
6)  $size
: Y% u, Y; Y& v( C& }: j
2 P7 C* w7 M5 j8 p0 n$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
3 f8 k' P0 T6 x1 e! u- F6 p- X5 I$ O- j3 X
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

+ q$ G6 Y2 j" b) w& X* `5 D2 l
官网上说不能用来匹配一个范围内的元素,如果想找$size<5之类的,他们建议创建一个字段来保存元素的数量。
You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

' Q) [; {+ y& {0 f- O
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    6 `7 {9 Z3 G6 {7 A+ f) q% l) J
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

- C2 z; M8 k0 {, N6 @
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string! R& M+ f7 u, j# l- H
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
2 V) Y! c; v. ]6 i( i
9)正则表达式
3 E3 G' Q0 {# T7 I, K. I) e
1 z# _1 m0 c& emongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
1 I6 Y: o: I: Z
10)  查询数据内的值5 z6 n( }7 u4 y3 R4 C* g
5 u9 f# _1 ^. B! q# W( A0 \" @3 a
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

9 l5 S* l: I/ a% |
11) $elemMatch
) W7 q" W8 v$ Y4 {% G/ S+ Q% k4 ^* }1 j% v1 l5 q' n
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) : I  Z: e7 r* p  m
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    " n4 ?; u8 ?9 F- S
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]2 Y; V" }; _3 ^( `9 b
  4. }
复制代码

1 ~+ f. v* H& {/ I$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
9 B8 ?- d% M. X  c
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } : v  p  \7 Y5 {/ @! {0 m7 F

; n: i: E0 ]" h; E9 O3 u- [12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
* I/ [9 B& J0 _8 [5 W
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
) Q6 ?! A3 s# F
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

. w3 W4 g5 J& A+ T6 p9 ?
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
/ M2 q. Y( U+ G2 U
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
4 ~* F5 r; B  f- f8 W* `$ s" b% ]( f+ y) i
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
) s$ e; f# V$ @
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );
    & Z+ p9 z) a! Z4 G+ j' h
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
3 y: ]5 d. E1 Q; J! G" M4 U, k( S
mongodb还有很多函数可以用,如排序,统计等,请参考原文。& t5 P% V3 F9 ~8 I" @: g

8 f+ [" N& Z; Q6 Q7 k6 W9 Fmongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
; N/ p1 K: J3 c4 }9 v/ Q8 T" c7 ?1 {  P3 r; A) M
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions) a, t  R  l4 E% I3 k% D' w+ o

7 o( g" M% m" V$ r+ d; R版本二:
0 J, Z' u- I  g" Y& M; n" f
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
1 m# p# Y! D( w* W3 r
  1. use admin
复制代码
+ e" b6 x' U8 c) g: q' P- l# l
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码

- o' g4 g* {' d
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

0 i. c% w$ s% G( ]+ c
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

+ U. K4 a) Z" ^/ g) f
         5. #删除用户
  1.           db.removeUser('name')
复制代码

: G, W: H- s# I
         6. #查看所有用户
  1.           show users
复制代码

; n0 ?3 @' q  \  z8 p# J7 p, x
         7. #查看所有数据库
  1.           show dbs
复制代码

6 {: @& z& T/ F0 U
         8. #查看所有的collection
  1.           show collections
复制代码
0 l# s0 g5 i* u; w
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

8 \/ U) e1 ?$ {+ i. d
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
" Y0 m7 Q+ O% Z3 N+ W
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

6 z% Z- z, s4 \9 t3 V8 D0 o
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
9 T$ V- g& J0 P8 B
        13. #查看profiling
  1.           show profile
复制代码

7 b3 O& s) v, _: f3 e& H' @
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

  R6 @, u$ p" N5 t' i
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

" G/ F* k" E1 K/ `' I, [, g
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
  T2 ]0 d; P. h" _5 t
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码

) K0 q4 F; @" `, R
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

& E0 [, d, q# o+ j. H
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
% _4 s# [7 x2 X/ l, A
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

+ F1 R2 A- `9 Z( o
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
# e5 r( c4 U$ H! m9 x
   3. 索引
         1. #增加索引:1(ascending),-1(descending)
         2. db.foo.ensureIndex({firstname: 1, lastname: 1}, {unique: true});
         3. #索引子对象
         4. db.user_addr.ensureIndex({'Al.Em': 1})
         5. #查看索引信息
         6. db.foo.getIndexes()
         7. db.foo.getIndexKeys()
         8. #根据索引名删除索引
         9. db.user_addr.dropIndex('Al.Em_1')
   4. 查询
         1. #查找所有
        2. db.foo.find()
        3. #查找一条记录
        4. db.foo.findOne()
        5. #根据条件检索10条记录
        6. db.foo.find({'msg':'Hello 1'}).limit(10)
        7. #sort排序
        8. db.deliver_status.find({'From':'ixigua@sina.com'}).sort({'Dt',-1})
         9. db.deliver_status.find().sort({'Ct':-1}).limit(1)
        10. #count操作
        11. db.user_addr.count()
        12. #distinct操作,查询指定列,去重复
        13. db.foo.distinct('msg')
        14. #”>=”操作
        15. db.foo.find({"timestamp": {"$gte" : 2}})
        16. #子对象的查找
        17. db.foo.find({'address.city':'beijing'})
   5. 管理
         1. #查看collection数据的大小
         2. db.deliver_status.dataSize()
         3. #查看colleciont状态
         4. db.deliver_status.stats()
         5. #查询所有索引的大小
         6. db.deliver_status.totalIndexSize()

/ y/ u5 z- l8 W3 |' r7 T; w: l$ Z
6.  高级查询
条件操作符 . i. D% f; ^9 |" A
  1. $gt : > 6 M. v: \4 V2 ^' p; E/ a) U1 @
  2. $lt : < " v- |. }/ l7 h1 w( Z9 A" ]
  3. $gte: >=
    * |8 O& ^+ B8 S! R# m
  4. $lte: <=
    ; [' k, m- R  |/ F2 y
  5. $ne : !=、<>
    4 W  W8 L) b% C
  6. $in : in
    ; p+ }; z" K( O9 k) v
  7. $nin: not in
    : w% w4 q+ r4 |) j7 ]
  8. $all: all ) k2 M; H, f/ z. V$ d
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
2 g( o; }# ?. p/ f! E
3 x2 l4 K4 z. j
查询 name <> "bruce" and age >= 18 的数据
% h9 ^% s( k: A: \3 Z2 n
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

  g: B3 \; M& N% r
8 x8 n1 G$ u* N9 i) A) ?查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
8 c/ U+ e- ~- b) y! r
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
. _4 r& @6 C) K* @# m8 Y0 K3 ]* ~
& {4 O) k8 [# e; V  p* |: o
查询 age in (20,22,24,26) 的数据   v/ H9 ]3 i; x4 @
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码
! G6 p7 Q7 c9 C  P! a( d
$ O% X1 N1 u* B5 t6 Y7 @: j% T9 Y% ?
查询 age取模10等于0 的数据
. N) ~# ?; q/ ^3 {; ?' z
  1. db.users.find('this.age % 10 == 0');
复制代码

( N5 ]' q9 m- P或者
! X7 v. X( s% r! V3 M
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
! w9 n0 j0 G3 W. p1 W- Y
# Z- w' E# d" V+ u* b# X1 G
匹配所有
0 b5 c! M3 \/ ], f) w
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
  ?" Y, W# m. L
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 7 w0 u$ F4 p. ~9 U9 k0 q
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
8 G4 @: Y8 U, s9 j! X: U0 N* ^
, a2 Z3 h- R* h& g6 c5 z* t" @4 f/ I查询不匹配name=B*带头的记录
) a" q0 H7 Z) Z
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

6 `. |; P2 }( t7 X8 T. {; P查询 age取模10不等于0 的数据 4 y- |7 O( L$ |
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

. \% K, ~4 k; F, D
: H0 r* J7 @2 j  x#返回部分字段
: {' v9 e8 r( H! c' [选择返回age和_id字段(_id字段总是会被返回) 3 t! i6 e/ M+ ]4 Y# a7 T
  1. db.users.find({}, {age:1});
    7 `7 x7 I5 x( _+ Q1 d5 c/ I
  2. db.users.find({}, {age:3});
    . ~  w! Q7 P5 ]+ d/ P
  3. db.users.find({}, {age:true});
    2 ~' E: t9 c) M' q+ V
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
$ Z* r! L% P4 ~, e4 ?/ {+ E' L
0为false, 非0为true
# s! o6 H7 L. v" L- ]5 k. W
% n. n7 s- t2 t6 c/ A7 T. _选择返回age、address和_id字段
' r4 e9 Y3 k3 Z; Z# {
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

: K8 }$ Q9 M$ U2 J. P  F, Z
7 |4 b: }0 S* X) T6 `8 r3 V# ~排除返回age、address和_id字段
5 G& H' S- z3 e
  1. db.users.find({}, {age:0, address:false}); 2 m5 p1 v+ w2 L( z. I* z
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

' J6 _- T# Y- m  |
2 W4 V  w6 f  g* F/ p# P0 T, [数组元素个数判断 # y& [3 L* ^% G/ o! W2 ?5 D
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 # c- a4 @4 v+ `7 s; V
匹配db.users.find({favorite_number: {$size: 3}});
. o/ a0 @2 z2 W, R( g不匹配db.users.find({favorite_number: {$size: 2}}); % L; B& Y+ v1 ~" F" ^
# C# |4 t6 F4 c* t( l
$exists判断字段是否存在 ! r9 y$ d, J; t
查询所有存在name字段的记录 " V5 c; S, G2 W- c" Q
  1. db.users.find({name: {$exists: true}});
复制代码

8 A7 G7 D: G: X查询所有不存在phone字段的记录
6 z7 g- p' H  E; O0 Z/ G& }6 f) ]/ o
  1. db.users.find({phone: {$exists: false}});
复制代码
4 d" t  n! e  `+ J! p9 m

4 s9 k) q! Y  V: r' r$type判断字段类型
  v" U1 i2 q! E0 b2 T+ n& {3 H( t查询所有name字段是字符类型的
7 r6 ]7 {, ]. m/ h; O2 l
  1. db.users.find({name: {$type: 2}}); ) `: s+ r& O" V" J9 L+ N: p
复制代码
6 Z0 \, |& Z5 |' `: u& J- {
查询所有age字段是整型的
: h% Q7 r6 q& Z' d0 }" U
  1. db.users.find({age: {$type: 16}}); ' w1 ]$ R6 E8 |! q2 N0 [. T
复制代码

* p8 Z) L- q* P! L对于字符字段,可以使用正则表达式
( C$ L; z0 o+ h9 g6 W/ C* B# f查询以字母b或者B带头的所有记录
: N! G* w- [# }' ]6 |  E; W8 O
  1. db.users.find({name: /^b.*/i});
    0 J2 Y6 u" c( c
复制代码

, Z( B3 h: ]8 e& [2 q% P. m4 @$elemMatch(1.3.1及以上版本)
6 A& _& Y3 z( k' H7 {5 ^8 [. s为数组的字段中匹配其中某个元素 ' I' N0 v* h* V& V0 k& S4 h& L

6 m2 l% b+ h7 ~Javascript查询和$where查询 % w4 b8 @& Q& P$ x# B
查询 age > 18 的记录,以下查询都一样 1 Z( `& p* X% j. B2 [# B
  1. db.users.find({age: {$gt: 18}}); * U( n. _, R! i4 Q2 P2 {
  2. db.users.find({$where: "this.age > 18"});
    : v0 @8 b# m1 S
  3. db.users.find("this.age > 18");
    " K5 h0 ~- m( ~; j. E" Y
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

) Z4 p8 Y0 B% R# r8 t
, q4 ~9 R; Q5 I, F排序sort()
3 m0 A" B  r( E% f' \以年龄升序asc
! Q6 b- G: F/ R7 }* V& j
  1. db.users.find().sort({age: 1}); 6 Q$ i+ a4 g/ m  i! _
复制代码

( g! z* y' y+ y. o1 {) ?0 R以年龄降序desc
$ ]# ~! S7 m  \
  1. db.users.find().sort({age: -1}); : C( w* W. q7 ?: G& E8 _; s
复制代码
+ M7 w- H& i, i* |1 p, \5 Q
限制返回记录数量limit() . `3 b; F) v$ _+ F, K( s. h( T
返回5条记录 & R0 ^; O/ C+ R" h2 f8 H- G( x: s8 p- A
  1. db.users.find().limit(5); 4 x. Q  P$ B5 S- z$ _
复制代码

1 ^7 ~; Y' h: v, X5 B9 ~" A返回3条记录并打印信息
4 D4 U5 U7 y3 f# p/ p) r' r: u7 s" Q
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); + G) w, W" Z9 w/ E* T+ f
复制代码
* \. n% U5 z3 m0 T
结果 ' `6 g. D4 y$ ^. h, h
  1. my age is 18
    . T# {& ], q+ C& N" \) G
  2. my age is 19 $ e* ^6 s- U0 I" O, w
  3. my age is 20
复制代码
$ s  d0 y6 u" Q7 s! j0 a
4 P  ~8 ~  I: B" a1 t( m6 x2 j
限制返回记录的开始点skip()
( }: s6 ]% o( d) i) \* d从第3条记录开始,返回5条记录(limit 3, 5)
* o+ S7 m" g: z3 z& P
  1. db.users.find().skip(3).limit(5);
    1 J+ y1 \+ D2 r0 ]) ~8 Q
复制代码

' L! J9 k$ D; f# S查询记录条数count() + R& y/ N7 e. ^/ E/ D
db.users.find().count(); . ?0 ~- [" j5 V5 b, s' k8 {% b4 @
db.users.find({age:18}).count(); 7 |' b( ~- h4 h9 x. [8 ]# u  d, b
以下返回的不是5,而是user表中所有的记录数量
+ e( ?: _) R/ p. i5 z3 |6 H/ O+ ydb.users.find().skip(10).limit(5).count();
8 x/ I" S/ n0 k4 F如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
1 t+ y# g% j$ F  `" `
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

1 k# z/ o3 y) V5 q$ b9 w9 \0 D" `; j' j5 S$ q5 q/ [! u
分组group() 4 t7 W/ n' q3 ]  m$ j
假设test表只有以下一条数据
. p, M/ T6 V. B
  1. { domain: "www.mongodb.org" + n: b8 \- u+ R5 b5 H) H- Y
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} + Z9 U2 S" R5 J" w/ q. [
  3. , response_time: 0.05 6 m8 @+ U$ E7 P' Y* k3 w: @
  4. , http_action: "GET /display/DOCS/Aggregation"
    # J6 o5 e+ s) F! h7 I5 d
  5. }
复制代码

; ]% \$ }0 t. ]) l( I: P/ n" L使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; 0 P8 }4 S8 v' @/ n, J
  1. db.test.group(
    + b, r: Z" K. l8 P: B) n9 |( v
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} % R  N1 Y" H. d) L: t3 ]4 W8 L
  3. , key: {http_action: true}
    / O( R1 ^! D" ?% Q0 U
  4. , initial: {count: 0, total_time:0} 4 i1 q' D% k& R& ^+ S
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    ( ?2 W' N; c" A8 G8 m3 r, @5 U) H
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }   q! O! W4 U! x* A; s; q
  7. } );
    # `3 M/ y* Q; E6 f7 o' l2 l# G
  8. , r* b  q$ [4 b% ?, ~( i9 \
  9. [
    ' |' r- [" H9 W5 s( Q! S. @
  10. {
    ( M6 X( \+ ]- v5 M" J2 x
  11. "http_action" : "GET /display/DOCS/Aggregation", 5 g) W  C1 @7 x4 k/ w
  12. "count" : 1, & x  V4 ?" o  C0 H/ R% P
  13. "total_time" : 0.05, % F8 f6 f( x1 B7 M
  14. "avg_time" : 0.05 4 i1 P  [) _2 O7 o/ k: x
  15. } 2 Z: ?+ `$ |# b: X. }2 a
  16. ]
复制代码

2 J( V1 o, G1 b/ P$ V/ }
. W* E% L) ]8 k* B1 f: T0 U% A' E$ N+ C2 h% |% K' u/ B
MongoDB 高级聚合查询
MongoDB版本为:2.0.8
系统为:64位Ubuntu 12.04
先给他家看一下我的表结构[Oh sorry, Mongo叫集合]
如你所见,我尽量的模拟现实生活中的场景。这是一个人的实体,他有基本的manId, manName, 有朋友[myFriends],有喜欢的水果[fruits],而且每种水果都有喜欢的权重。
很不好的是你还看见了有个“_class”字段? 因为我是Java开发者, 我还喜欢用Spring,因此我选用了Spring Data Mongo的类库[也算是框架吧,但是我不这么觉得]。
现在有很多人Spring见的腻了也开始烦了。是的,Spring野心很大,他几乎想要垄断Java方面的任何事情。没办法我从使用Spring后就离不开他,以至于其他框架基本上都不用学。我学了Spring的很多,诸如:Spring Security/Spring Integration/Spring Batch等。。。不发明轮子的他已经提供了编程里的很多场景,我利用那些场景解决了工作中的很多问题,也使我的工作变得很高效。从而我又时间学到它更多。Spring Data Mongo封装了mongodb java driver,提供了和SpringJDBC/Template一致编程风格的MongoTemplate。
不说废话了,我们直接来MongoDB吧。
  • Max 和Min, J! o. d/ G5 W1 F/ T) \9 `
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

1 L3 I9 t+ \8 r: N+ T: \  f7 r3 a- b" B

  |3 r! q& w2 i4 H/ O
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct- A! O) [- E$ D# h' F% R$ i# n
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
1 K# x" p- D! G& g0 y( o6 l- o* x8 O

3 q6 C/ `7 G9 o
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

- p5 P' O0 ], ^4 n/ P/ r) Q* o0 ]/ w9 ^5 Q: E2 p2 j0 w
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

3 u! }! H* S# ]9 B4 O# N/ y
3 c  \2 ?7 Z4 I0 b4 Z
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

" b6 N& m! z# F5 f
1 o  w. f; [- l
输出如:
  1.         
    8 g: x/ Q8 `2 |
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

. x' |& O& Q3 v  W& @: T+ L* K2 q& f* a" `- v
. e' y: w; D3 W, D3 Y2 ]
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"
    : G4 @5 o8 h. t' s
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance". H2 g+ V3 L0 Q
  3.        xmlns:context="http://www.springframework.org/schema/context"
    ' l" \2 n, s7 V  G$ w# L
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"  |3 n+ u! A( T: S# |
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    5 s1 p- C5 ?. p( x) l
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    ) |8 ?* _+ }3 n* q$ x
  7.           http://www.springframework.org/schema/context
    9 Y' B3 N/ o+ m* M. |( V
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    8 M8 X7 _0 s9 V1 r) u; c
  9.           http://www.springframework.org/schema/data/mongo3 n' A. A2 ]& X
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    & c% q( h- H' p  m4 l' z( U/ g* N

  11. 1 e7 @/ Z: |- s! T
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    % Q5 d% }( G" ?# p. G" J4 J5 N

  13. ' q) Q- h; v$ Q6 Z7 p
  14.     <!-- Default bean name is 'mongo' -->
    7 f/ b! r+ E& O' A. f
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    ' |6 P8 S0 Y7 f& ]* Q* m& Y3 F

  16. 8 x' H# s" `; j7 Y/ o# r# j/ V
  17.     <mongo:db-factory id="mongoDbFactory"
    - i# K4 @, Z; J* E$ c# p7 P9 O
  18.                   mongo-ref="mongo"7 V, C5 {! c. A& g
  19.                   dbname="mongotest" />9 D8 Q1 h$ g$ B( I5 C( b( D0 p6 k
  20. + o- D" D) s  L, ^- S' m1 |- u
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    4 ]/ n- n- m. d; \$ q, w% u
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>0 m6 N" d0 \- o$ ^2 J8 d8 @, H) N
  23.     </bean>
    $ f& \6 m; Q2 T3 c1 Z
  24. </beans>
复制代码

2 M. q4 ^- `. F+ P4 ?
8 b* _3 U8 J& O/ p9 ?' ]
maxmin的测试
  1. @Test
    " `% u( f9 d( G. A
  2.     public void testMaxAndMinAge() throws Exception {
    , c& m: r9 c2 ~: m& M. V, p1 Y
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    9 {/ Q! G! R; W3 l& a, v* B+ o; S
  4.         Person result = mongoTemplate.findOne(q, Person.class);1 A; J) c: P' x; w0 H
  5.         log.info(result);7 l2 Z4 n6 ?- y9 F3 T
  6. % Q7 z2 C, P- T' T/ O/ B
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);+ G2 p5 K- j7 |6 o5 Y* o: g" M. z
  8.         result = mongoTemplate.findOne(q, Person.class);
    8 K) C. \7 n6 L
  9.         log.info(result);# t* y* ?% C& f# k4 v/ c
  10.     }
复制代码
( B, J* ?! }  y

. ]- M" C* z' f5 B9 d% n. ^. Q- Y  A
distinct的测试:
  1. @Test7 _: o8 U* K0 V( l. _0 A
  2.     public void testDistinct() throws Exception {( t/ a3 N6 Z, B/ }9 U7 V
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");2 M' v# ]( M5 B! F7 _! I! o" `* O% v
  4.         for (Object o : result) {+ l6 z3 F0 V8 @  p
  5.             log.info(o);* |9 |. E" j. u6 c) B5 |$ M
  6.         }
    % T7 J# S: p- P) P  Q. a3 _$ O6 I
  7. & o6 c8 ?/ s1 ?( z0 d. l
  8.         log.info("==================================================================");" S) R/ z3 ?8 ^+ J, ~& A$ |5 n
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));- y  D. U/ G  ?" l4 `& J
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    4 f* L/ [( _9 l; y" k" C
  11.         for (Object o : result) {: s7 m& e# f3 b1 f, c
  12.             log.info(o);
    ( [: Q! V( M/ ^
  13.         }: n2 N. R' g7 e0 e; u& U) @! ^

  14. 3 w, K! R5 j7 [5 q! u( [* [9 j8 _
  15.         log.info("==================================================================");
    2 b) \( Z, v6 T0 @8 P
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");+ `' a3 @# h. @' c% |1 R
  17.         for (Object o : result) {1 p; K  w6 s% g. J2 w8 f
  18.             log.info(o);! n3 \  W0 F/ L# k
  19.         }) B6 Y, \& _; z6 j" \0 D8 z$ V
  20.     }
复制代码

3 _  _: Z- {- R1 e# ?2 e
( a/ Q/ e: v; o6 V1 r- o% f
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    % C) c9 s4 g0 o; G& c
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    , I- `+ C( K) Y! q& J
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 4567894 U$ r5 `0 w" g: }
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
    4 W& l( ^- s$ h  H5 Y" {  A! S
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni( [$ l3 M  C* L: f
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    6 T4 T. \( W& Z% j) E. Z, m9 O
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    ( C- F# \$ ~9 }2 n+ T9 P
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    3 A: n" t6 a. Q. {+ f6 O
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567% H' d+ n0 r7 O% l
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 3456781 v8 Q, j- i, K0 W5 O
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    # @9 I- s& {9 }3 E7 P
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    4 w$ d7 x2 x" n2 \# {
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    , d# X  J' r0 N+ F8 {
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa2 d) ^1 N( b) ~
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb4 a* v$ ?4 i0 ?% x  f5 t% C
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    3 u, c" Y+ X! D3 K) e3 Z. i  t
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    1 u! g* _1 x# z5 @. j
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx. g& c# J# ?# G0 [4 z: ^2 S* n9 B
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    0 o' r) ]2 Q) {7 H5 o7 r% Y: ]9 m
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz3 N, b  Z7 S" r+ L7 A$ g
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr* |" B; E* ]: t5 ~/ x7 f
  22. 12-22 14:13:45 [INFO] [support.GenericApplicationContext(1020)] Closing org.springframework.context.support.GenericApplicationContext@1e0a91ff: startup date [Sat Dec 22 14:13:44 CST 2012]; root of context hierarchy
复制代码
; S! n! E" U5 f& _% _

; w  o2 c' z2 t
这里我要特别说明一下, 当使用了Spring Data Mongo,如上面的findOne(query, Person.class)它就会把查询的结果集转换成Person类的对象。Spring Data Mongo的很多API中都这样,让传入了一个Bean的class对象。因为distinct的测试是输出list<String>的,我 使用的mongo-java-driver的api。他们都很简单,唯一的是Query这个Spring提供的对象,希望读者注意,他几乎封装了所有条件 查询,sort,limit等信息。
. Z/ C5 l2 l; y8 `2 _9 n9 e! r

, f. I1 z) h% ?' x5 A
: h2 @9 f0 R4 {: z5 @
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-19 20:17 , Processed in 0.138788 second(s), 23 queries .

Copyright © 2001-2024 Powered by cncml! X3.2. Theme By cncml!