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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:
& q5 e; }9 ^4 j2 z% `
( X8 q( O1 u, Y; B1 ) . 大于,小于,大于或等于,小于或等于8 b* |/ v6 \, j6 m* D
$ M* ?6 Q& |9 a
$gt:大于
, g$ v  H! b2 @0 W8 U; V$lt:小于  ?( _! {* L' v& A6 D' [, v7 D
$gte:大于或等于2 j5 M  j, d9 W' f, \  m
$lte:小于或等于
  C4 G8 J' S9 `+ w. H+ r7 X
9 G1 j0 k' F/ H6 \8 x  D- ^+ d例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value6 ?% s. C0 s! c4 G8 a$ X
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    - E' ?; Y4 l$ `0 ?9 V9 b) _
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    ' U6 w3 ~; q* I+ Y. J" K* n
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
; b8 Y' y" O& o7 h" M, e
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});1 S1 h2 v: X- ], P- [% p; z
  2. db.things.find({j : {$gte: 4}});
复制代码
8 y! B! v9 i4 t  ^6 J" T
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
  |' w& P0 W1 X  p& G% Q
- |# P2 `, c  p% r

( d3 ?- }& ^+ D) L+ x
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
' ^* x% d+ V/ {1 Z
3) in 和 not in ($in $nin)
  E$ {% y/ ?6 i- F4 L5 N0 ?  l* U0 J5 o  Y- R
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
* }$ e1 @- z: ~* t/ T/ S/ W+ r6 d
例子:
  1. db.things.find({j:{$in: [2,4,6]}});& ?% ^" Z  t6 U: ]/ x
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
  l  O! p) n$ t: |: q  R6 Y: p

: a4 \7 [: P% p* p) P1 e4) 取模运算$mod
" _! k: o1 K+ a# A1 f. g7 N
7 u) [# I" L, D) U( Y% i如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
$ O: v0 X+ t% n
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
2 E8 |7 n9 ?- P% J
; z7 m8 {6 a+ M1 h
5)  $all" {+ S* O* Z+ U1 N9 s

" l% J+ C5 A& G0 h$all和$in类似,但是他需要匹配条件内所有的值:
1 G* ^/ a9 H9 y5 d6 {! c8 D
6 o& p9 K* x5 I! J2 J6 B- G% B如有一个对象:/ `( ]- r, i% o2 @9 U0 D
  1. { a: [ 1, 2, 3 ] }
复制代码
0 V$ }/ J" L4 @& m2 C$ J- Q
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
1 s4 I, H4 ?. y9 e
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
* G8 I$ }5 }: j1 y3 F
3 j/ ^4 h2 n& j( ^! t; {1 A
6)  $size8 l, r& p; V+ M. G* C

- v9 N0 p! F/ N, G  \* d" u$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
  o* B& M" w2 a3 O# w, Z! f5 W, U
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

! C/ g2 p9 l& J1 M' B& }
官网上说不能用来匹配一个范围内的元素,如果想找$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.

1 F1 N  G# G0 g
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    2 j) i! \# |& g( h8 o/ Q
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

9 Y# |7 e  O, G! P- i1 Z. w
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    . N( H$ t$ ]8 c3 e
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

) H9 q9 p1 E8 S$ {. h( ^! D2 C
9)正则表达式
5 u8 V+ [0 ?1 D7 U* m, K! P# a: S
; b5 [( L/ X, v/ Cmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

5 t4 w" A) Y/ M  z/ Z9 d4 P
10)  查询数据内的值
$ y! u/ m4 O# O9 f' f+ k3 |/ M' Y6 E
2 ?  x8 r& r* a7 C: j下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
( `2 Q5 v8 y# O" Z- J5 t9 a5 [$ ~
11) $elemMatch3 A+ m5 W5 m- d9 o1 Q/ B' X- Q

$ a) ^2 r' j; ?  L. N如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    5 f, b& N- i- G
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),    T0 `3 J/ W1 X
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    8 k, {4 t/ i0 z4 a
  4. }
复制代码

2 j- t2 k. O4 d  Q9 a# @9 r2 k$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )! @$ O! P9 Q. a# i& F- J+ I6 W
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 3 k2 Y& z( R2 X6 P
8 ?, ]; ~  c8 Q) Z
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
; K- u% E) _9 ]( ^, c0 z
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
5 h7 i, t$ P7 j/ `, v- a8 l# m
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

1 _' z9 S9 Y  ^0 M  t' n2 Q" ?; P
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
1 e' C* R) {: u% L
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

2 ~) C& C% B: O6 `9 U
是不能匹配的,因为mongodb对于子对象,他是精确匹配。

2 [, E. C0 S+ t
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );; w$ t' q0 ^' v# B2 k
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

2 x2 ^- k) z! X3 i( l4 B; b( p
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
1 P; I7 f7 P" \* E0 b" i% y! R, H9 z; m
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
9 [. G( T- P9 E0 ?: c7 J: `2 e' k# B  X' D
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
* P7 J/ S4 P1 ]' M# R# _* ]+ }  m" _: w  d4 J
版本二:- }/ g: `9 }4 |+ v% R
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
$ l" e) t& e) W& y2 ?! S6 k
  1. use admin
复制代码

3 v- h; C0 a! q% C+ x) U0 ^
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
. I. @1 J6 Z7 D
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
1 V+ V" n0 l& H' ^+ V0 t" H
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

( T, V# S  `6 J
         5. #删除用户
  1.           db.removeUser('name')
复制代码

* @5 ]0 j  G- O, F4 N; y5 @
         6. #查看所有用户
  1.           show users
复制代码

2 t! m, V. @$ d1 k1 U( e
         7. #查看所有数据库
  1.           show dbs
复制代码
) S: z; @& u! |6 R
         8. #查看所有的collection
  1.           show collections
复制代码
+ D* t% c3 G  Y
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

( \% P% }1 z) a0 [$ V, _
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
' s# V, f9 T, B' W9 P
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

3 p, N; B' k5 R& c7 j$ z( O
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
" V7 P* R2 w8 Y+ ?- q- {
        13. #查看profiling
  1.           show profile
复制代码
$ @% {1 [; F. H
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

; @  L7 P! s1 Y0 W& b2 C
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

4 L! _7 i: O- r# l
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

3 ~; u- z& W2 ]7 H
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
4 n2 d4 [2 n6 d3 M$ @) f; J% P% V% i& c
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

$ V$ C5 A. |3 E2 y5 E
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

) ?" v* V9 s% A
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

' ~- [0 C4 f( x& j7 o* m
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
7 C  F; u3 m% i8 n
   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()
3 \+ R8 ?2 M: \2 I9 w
6.  高级查询
条件操作符
& f) n' q- G4 m% i" x: L& c- \
  1. $gt : > - j6 V+ }; ?2 Z" |
  2. $lt : < ' Q; |1 q+ w) [
  3. $gte: >= 6 g1 G) X# @. L" k; ?
  4. $lte: <=
    - U+ k# {; m, l  W1 o" _
  5. $ne : !=、<>
    4 o4 X, `  n& v3 o- ~9 S2 t  ]
  6. $in : in . ?  e8 |2 R6 n' S( t( U' a
  7. $nin: not in
    1 X, X3 A- k6 X/ J2 h1 ^* x
  8. $all: all
    , h( v  {2 P* Z1 k/ p3 o+ i. }
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
  s' E  X% E2 o! I; k+ G4 O$ a

: ~* \- i; h9 b. D# I查询 name <> "bruce" and age >= 18 的数据
$ ?! ~) S1 l: ^3 k
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
, ^  {- x; R% }( B. q; p" s
* p0 r$ R1 b) n; u  T# }+ h6 c
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 & _& h1 Y- q5 p! d
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
1 l; a% p  U2 j  q' m
8 ^2 h. ]2 Y1 a( U7 {
查询 age in (20,22,24,26) 的数据
# X: s2 j# h0 G8 n
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

/ y% X/ W: J* `
* j7 G7 r$ A8 i" E' n; f查询 age取模10等于0 的数据
/ q+ Y: q' c" _3 g% V
  1. db.users.find('this.age % 10 == 0');
复制代码
( n# _( D6 }5 O% M  R
或者
$ Q$ h$ L  u5 [8 D# w7 k( A
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

$ V/ _# x. o' S
+ y+ F6 R8 S1 ~  R4 d* d匹配所有 % q! |4 |; F3 e5 b
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
8 k  l# B+ i7 Q9 u$ j6 t8 B
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
1 {2 Z: V8 Y7 e, h$ N可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
. `$ }6 _1 p) L, f. d
3 o, p4 o" w% g. t: A8 _查询不匹配name=B*带头的记录 ) `" _$ L4 K1 I) R; l6 ]) `* }3 I
  1. db.users.find({name: {$not: /^B.*/}});
复制代码
% `+ R7 H6 z; y* ?5 ?! T: |
查询 age取模10不等于0 的数据
6 Z1 a# X: A& R* [" n
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

. |/ h: b7 W" \) [) v1 i$ @; a0 l# Z5 n8 I" Q
#返回部分字段
- v# E: ]6 l" w' x4 b选择返回age和_id字段(_id字段总是会被返回) ; {; S+ n6 `& H
  1. db.users.find({}, {age:1});
    % f' g1 R. K3 J) w# J- p. t
  2. db.users.find({}, {age:3});
    $ c7 ~+ H' K" F( U. J! _- y
  3. db.users.find({}, {age:true});
    . g: D3 X, |# m( ^, N: K
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
7 V/ Y( D; q: u
0为false, 非0为true - u; i; w( M9 Q0 ^' [# W

/ U7 B: g  ]- i选择返回age、address和_id字段
* ?# N* W6 [2 c# q
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
1 E( X* }5 a, q; q$ [$ P) S; o1 S
; b, z* a: S' c; I& |
排除返回age、address和_id字段
) u+ K3 ~( f) q0 G
  1. db.users.find({}, {age:0, address:false}); / K1 Q1 [3 W# Y4 L2 V- b, B
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
0 d5 n1 Y' Q( @. j& {, |1 E8 B- T
) l" A- R  f8 F9 S0 f' H# @3 s
数组元素个数判断
  c  [7 k) \* s. b' b7 u( [1 [对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 + n! @2 E3 |* R  e
匹配db.users.find({favorite_number: {$size: 3}}); . O$ p0 j- |+ b( M% r5 h/ [
不匹配db.users.find({favorite_number: {$size: 2}});
3 ?* g  K3 y) p6 q8 U6 n, j. @7 M1 ^. L. _- T6 m3 K6 B; c- r
$exists判断字段是否存在
. S3 [6 O! p6 b& ~' o" b8 g查询所有存在name字段的记录
6 Q! e! q2 N  u2 O. U
  1. db.users.find({name: {$exists: true}});
复制代码
  F  u$ l0 c; F  m0 D2 \
查询所有不存在phone字段的记录 $ O! T) B9 H0 O/ X5 e
  1. db.users.find({phone: {$exists: false}});
复制代码

/ V# Q0 |% A' N! o. u" U+ f2 e3 a5 `$ {
$type判断字段类型
  [2 a; y/ n7 g- P/ Q$ w! K查询所有name字段是字符类型的 8 g9 Z1 N- H% t9 p5 [
  1. db.users.find({name: {$type: 2}});
    2 w: u' R' Q0 O
复制代码
! D8 V" U6 j* m* M& j
查询所有age字段是整型的 $ w, L6 X8 p0 i2 k- ?, j/ h7 C
  1. db.users.find({age: {$type: 16}}); / }# p. a6 b3 j+ X
复制代码

$ W: @; W8 K, J5 Y- i对于字符字段,可以使用正则表达式 : O9 V2 I$ N5 [7 \: l$ J, w2 K
查询以字母b或者B带头的所有记录
& r0 M7 i4 ]$ o/ x# ]& V* F
  1. db.users.find({name: /^b.*/i}); 1 f. [& j) A  J" c( I+ C$ J
复制代码

4 k. z7 ?- _+ |3 g6 E- d5 l# ]9 L$elemMatch(1.3.1及以上版本) + \6 K0 ]/ ^5 K, M/ ?# n
为数组的字段中匹配其中某个元素 * i3 P; F3 ?) q2 `& ]$ R
7 c, v3 e! g, r% H2 D7 ]
Javascript查询和$where查询
$ W7 w& b5 K* {9 x7 a1 e查询 age > 18 的记录,以下查询都一样
& w9 m1 c2 t! A& k/ Y! ?
  1. db.users.find({age: {$gt: 18}});
    7 k2 s6 M" X4 b
  2. db.users.find({$where: "this.age > 18"});
    . `0 }" V6 @( {3 V
  3. db.users.find("this.age > 18"); & J& \* P4 ~/ ^
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
6 n# ^* ]/ W, V
1 m9 n3 W1 H$ v
排序sort()
6 k/ j3 L9 M: l; {2 X0 I' E4 @以年龄升序asc : _- u6 h, A7 X  Y5 L6 ?" h1 O
  1. db.users.find().sort({age: 1}); / K3 y& A; W0 P( l; p8 D. r
复制代码
$ I( o) ?) n: ?1 C7 F
以年龄降序desc
3 }; b& O" k0 R/ g5 Y/ U7 C
  1. db.users.find().sort({age: -1});
    ! B9 `5 ~) w7 v3 k* L
复制代码

7 s9 T" Q$ p( P限制返回记录数量limit()
* y8 I+ @& [) |. {" c返回5条记录
: e, u3 d; {- R" b% i$ B
  1. db.users.find().limit(5);
    6 Z$ U+ U+ W9 E" T6 w( g
复制代码
) M1 p8 b# ]$ C( N. B8 x$ }
返回3条记录并打印信息 + b2 P% J' p3 L5 `2 f2 r
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    . G, W# t; k9 u8 O5 m
复制代码
% P3 h& @+ }0 _  i$ A4 N
结果 5 P. Z6 o* s# B5 _( L
  1. my age is 18 0 g& \, F; Y! p3 e) p0 u9 N
  2. my age is 19 ! w" N# s/ H( o  ~% t; L8 b
  3. my age is 20
复制代码

! v  n5 x! v4 S/ _+ W) o: V( ^" k& B
7 U0 ]" D$ }8 R% V% x限制返回记录的开始点skip() / _# o+ @9 R4 @" ?7 g1 b/ k/ E
从第3条记录开始,返回5条记录(limit 3, 5)   }8 ~. j  w; Z+ ]
  1. db.users.find().skip(3).limit(5); ! B8 M7 t- v! t( c
复制代码

) H2 D, {! j  @% ]* F2 C查询记录条数count() $ K6 \; Z! ]+ {; J* a' K9 l* Z
db.users.find().count(); 9 z9 ]. w, _$ I/ r% b
db.users.find({age:18}).count();
# j5 G* X, c) b& ^; T6 v- I$ p以下返回的不是5,而是user表中所有的记录数量 ) r, O# p$ U$ F% G$ B# v9 ~, r
db.users.find().skip(10).limit(5).count(); 1 l3 B: L% R, N
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
. _% y! d0 Q# H6 J/ z
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

5 g: G  A4 \& X' f* {6 j: L' w; n9 Z
分组group() 3 x  f, d; `9 h. F7 u. q; D
假设test表只有以下一条数据
" s2 w# a' `7 w: `
  1. { domain: "www.mongodb.org"
    ) I6 @! c; a& }1 `, i' h8 g
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} / e, @4 O$ z. e
  3. , response_time: 0.05 " x/ L- ^8 V/ n9 P% C* j* |% t7 C
  4. , http_action: "GET /display/DOCS/Aggregation"
    ' D9 }" B  J  r; I$ m
  5. }
复制代码

% X9 b. E) W) X1 J. @1 N& n! O使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
; L& \, q, d; a! [  s& h9 a/ l2 p
  1. db.test.group( " m/ J$ F9 S' o
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} % {4 f0 M: n& A' h& @7 l: H3 C
  3. , key: {http_action: true}
    / t/ A' I, \+ Q' H8 X
  4. , initial: {count: 0, total_time:0} 2 H. C8 I! _# w! y
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 7 Z, `: |( J4 p/ [
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } 0 _% b) h8 h1 ]3 W# v
  7. } );   \, N, U* M2 X7 ]6 }( O- E
  8. 5 f7 ~, J& E! ?1 q+ g
  9. [ ' W7 R) n3 u! T, H, c+ Y
  10. {
    . U* j3 R/ t8 U1 F
  11. "http_action" : "GET /display/DOCS/Aggregation",
    8 A3 w! s! l0 a& f* f: W
  12. "count" : 1,
    6 w  h/ b! b, I- x3 ?; h% N6 w% p
  13. "total_time" : 0.05,
    $ n+ R3 U$ M  c! K; W
  14. "avg_time" : 0.05
    ' {* \" t9 C% G. g! D
  15. } & u0 J4 c" r: Y! `. V
  16. ]
复制代码

( ]2 w8 [% C6 h+ X/ P- M9 z3 C( d! ^6 L4 ?6 M
4 \' y3 T6 F; B+ L
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 和Min7 f( r2 Q$ E* q- p
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
" N0 D" i6 I7 d+ G
% W- \" f' ?5 n. z: e, w6 G
, p* G6 r" ~4 l, {5 u/ b! o
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct7 m9 H0 e( [( U
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码

, S# `/ m0 M# I! m4 q# G1 b0 i) L9 ]9 ^1 e5 h9 M' b/ C* X9 n
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

  o# F( H1 o3 `2 _% n9 U5 O4 |) ^4 G
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

: I7 R% s  m& S5 ~: q' d, U" _. y4 E. m' h! D' _
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

$ U# f! o: x7 v* e  J9 x
- l* W/ C& U7 G5 H, v
输出如:
  1.         
    + p( [+ I6 T( A1 f5 v3 c6 E
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
* s& ?( ^) e* l/ J- p4 V

. n* c9 b/ Q0 M* e7 \# _
/ W# R* J5 O+ Q' u9 ?8 d
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"' K# t: G! f" X- r
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    . C6 Z3 `4 H5 e/ C2 E! F
  3.        xmlns:context="http://www.springframework.org/schema/context"0 |3 S7 d# L" w. r
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo") g- x7 X9 j; a6 M
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    * }2 S  A4 o, `0 f
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd* o$ w! [# }8 y
  7.           http://www.springframework.org/schema/context
    . g5 N9 C# I8 Z- ]' B7 Y0 f6 V
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd0 r0 {; z; u- _7 n
  9.           http://www.springframework.org/schema/data/mongo& k% e$ @7 U2 ~/ D
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    + L- ~8 _$ F" g: F6 O

  11. & h* \; u0 B) T/ b+ {) a$ u5 W
  12.     <context:property-placeholder location="classpath:mongo.properties" />0 X! ^; l6 T# `: M+ e. V: W

  13. , A2 }6 W  Q/ T  W
  14.     <!-- Default bean name is 'mongo' -->
    ' _: v( h9 @* o4 Y9 {( Z" H: N# o
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />. A9 j: T) F# d6 l4 ^
  16. & ^& v9 u3 [& l
  17.     <mongo:db-factory id="mongoDbFactory"
    ! E! i5 q. c0 T
  18.                   mongo-ref="mongo"0 z) h) p' Q7 n
  19.                   dbname="mongotest" />* U2 f' ~0 o% V+ Q4 s
  20. 1 b: O8 _. [% \' o* x
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    " P; J- N! s8 V; z6 M" w8 o
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>6 {$ g$ \6 Q; V5 Z$ d+ m; A! C6 S
  23.     </bean>! |* ^. ?6 c1 ]: O' G, Q
  24. </beans>
复制代码
+ W6 L( ]$ B/ c! ]) r

- c: u2 g+ ?! M4 a# \
maxmin的测试
  1. @Test
    % c" U9 n! \" H
  2.     public void testMaxAndMinAge() throws Exception {( C) T. z6 d- |' K7 @
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    5 i' f5 c. [/ q& N  `7 W
  4.         Person result = mongoTemplate.findOne(q, Person.class);
    ( L, `& p* ~. z% x8 p! n! z
  5.         log.info(result);
    + ]' r* E. r+ {' ~4 U5 N8 G& |

  6. 2 I5 j: z- z! w" M
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    8 Z5 c0 _8 D1 ?5 i% J
  8.         result = mongoTemplate.findOne(q, Person.class);
    6 j# A& }7 Y2 ^: D4 X) ~
  9.         log.info(result);. _9 \3 l4 V0 ?' o9 d
  10.     }
复制代码
9 E+ `9 ]3 C6 W; P: s

" _+ V; u5 R1 R, E1 L1 l8 f
distinct的测试:
  1. @Test
    8 K& I2 ]; Y5 h9 g8 X
  2.     public void testDistinct() throws Exception {
    7 O" d. [6 ^+ G. q" Y2 r8 W
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");3 ]2 L. U2 U. B8 ?& `2 A. \
  4.         for (Object o : result) {
    ! d) C7 t' V4 _/ v) o
  5.             log.info(o);
    5 P7 C7 S8 ~- L. [6 Q! J6 u
  6.         }
    8 y5 i  ]: g& }2 B/ v, f
  7. 9 |; O5 b5 N; Q0 w
  8.         log.info("==================================================================");* z/ _3 K9 k. r3 v" s6 \
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    ! s' _, P# s* E8 D
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());! m' \( s6 I5 x5 u8 g  v- h9 v
  11.         for (Object o : result) {9 D% X. B# u4 R0 G  c5 Z/ w8 J" |
  12.             log.info(o);
    ) T3 O) O, M6 Z; w" n
  13.         }
    # |+ ]$ I+ j- w7 F
  14. 9 }- |! j9 p# |; f. W& z2 \, L# o
  15.         log.info("==================================================================");* F  `: e% l1 s% o- E, p7 A: s6 n
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");- e& \/ H- I* S
  17.         for (Object o : result) {
    5 N% q& D' o' p2 R8 r0 D" S& l
  18.             log.info(o);
    # H0 ]" l7 |) u( ^7 A1 M
  19.         }
    / W1 \$ P+ ^+ A9 I4 R$ C9 i9 [+ z
  20.     }
复制代码

+ [1 \% U, C1 Y/ \0 w7 m
: m% F- |, p, c2 k- E- y
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 2345674 z; @. C" o9 r) a0 j
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678+ n# @) N- [6 R, D
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789, w' S& p; {0 n0 k
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654* V  r, t# g& J; j  z: m( @9 |
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni' N0 Q& q& w8 l6 |% D* \
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo; ?+ n$ m. ^; Q+ v! w
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    * X* j# m2 L$ N8 J
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================- l$ I; P! K" M$ u! R$ c* C
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    8 w. P! n  [) h* ]8 g
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678. ?. Q* q- P( c
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 4567893 k8 C# V, }- A2 @5 ?0 b
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654' I8 ^7 F5 ~7 ^8 Y
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================" E: _' Q9 t% w- x
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa+ w; a* a* f5 D; u9 x9 ^
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    9 j: N2 E9 W$ ~
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc1 Z$ E* g  [2 }' \+ d
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    2 ^  Y% w/ t' V- g. M# ^$ v9 z
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    % C/ F# X8 O$ u. z1 k3 M8 q+ n: C
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    2 l; z+ [2 v8 l( |$ J* W; L
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    & n  E& i' A/ j) o. s4 z- `* |8 D
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr7 D3 }+ e0 x: o# V
  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
复制代码

" t6 T" A! u$ v; H* i8 {1 ~: s! V8 ?2 `: i( Z
这里我要特别说明一下, 当使用了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等信息。

5 C9 A; W; e1 x# K4 f( f% s: E
+ h8 R1 }) R1 ~: c, {+ Y- ~5 d$ m; P
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-8-4 12:39 , Processed in 0.064569 second(s), 22 queries .

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