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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:
! ?) D2 {: K# n/ Q' _' b
7 z( \" {4 L) L2 d; Q7 a1 ) . 大于,小于,大于或等于,小于或等于3 M: Y) n8 d# K( N# f

0 W0 P( l3 J( |7 b  t$gt:大于
0 g; R6 Z0 s  p8 s5 n1 [$lt:小于9 T; B" E3 B3 p4 Y" E2 g1 r4 e
$gte:大于或等于$ y( I$ |; _, k9 C8 d# K+ Q
$lte:小于或等于
/ ^3 O$ @) I. p  |9 r* ]% j8 U8 h' v4 y0 N
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value, n4 ^  j! c) o. d# L
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value" \. K$ Z5 Y1 _6 T
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    # A+ Q, n& k: m
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

) M8 y8 Y, g" W" Q
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    " Z* a/ A0 \) y- |3 a# q' V" r
  2. db.things.find({j : {$gte: 4}});
复制代码

% b) j, Z- G' ^% D  R3 K/ P
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
: N& m, H4 P/ i' }2 p: |
6 p& M; H) U4 M& P
" {9 M& E6 Z/ P
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
/ N3 M1 Q) @- A) ?  g& M7 G
3) in 和 not in ($in $nin)3 ^& Y. J( T* t2 h' R4 c* l0 U8 D

3 G  j* x' o5 k4 B, q* X; }" t9 W语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

' I9 }( K6 o8 {( K/ z. `* x0 A: A- a' v
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    6 R7 _* `5 H4 w/ `8 j, ?9 F" q
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
0 g! L. A2 E/ z: T
/ D% W2 f( r& h4 K$ b* M
4) 取模运算$mod5 Q0 F# P. A6 {: c' B, @5 e5 H
+ }' w. o% ~# h1 \) M6 C0 P+ ~
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
- T, O$ K' q" n! G. q
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

0 \8 g( {; x3 H8 h
  u9 W, [" J* c& u) x- E$ N
5)  $all! P  K' w8 L. u5 l$ h4 ^

$ @1 J" j5 J2 \6 h$all和$in类似,但是他需要匹配条件内所有的值:, q. Y' ]8 c" k9 x3 o

% ?3 |* B  _% o3 D* Y  ^如有一个对象:* `* Q: S8 H5 p7 W9 O! O, `
  1. { a: [ 1, 2, 3 ] }
复制代码

8 A* R7 V/ o: m2 @
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

3 g. \+ m' k3 h
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

- ^" f( X; A4 M
+ r$ f( S5 x2 m6 C5 U& O8 ~
6)  $size
) p5 M1 S+ H( I$ d
' ?' p5 [  J' O+ A$ }. y$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:! x$ P/ Q: w9 R7 V: q
  `: ]& A/ C" s+ o( n6 E
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
6 h9 ]2 f  T/ k/ B- a0 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.
* T' ^' X- D. t( S" {6 B, d
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    . y, K8 Q0 U0 o
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

3 M* s1 Q3 m/ ]$ j( V. T
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    ( _* O$ J# H7 P" k$ z
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

- i0 a, O! W: A
9)正则表达式8 Y% w' `4 V7 Y% Y* B/ V1 }) F
; [1 D. y6 J7 z0 e) b$ w
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
( Y: B, Z. J7 W1 P
10)  查询数据内的值, Y; K/ Y- M6 g

; t! S9 B4 d* B" a5 A8 ^# P! U下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

" H) a2 ]7 M  C+ p. R! R& A, v
11) $elemMatch
: ]7 M+ U' ?, b4 g& B" h4 v" |
9 g5 \. O( r8 {# x; W3 \如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) & K$ T) W- r" S( D0 D- q& t( Z/ @
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    & \' n- b* J, ]3 V6 B2 Z  ]
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    + k2 D/ D& ?# F. b
  4. }
复制代码

- q, x: q3 r3 V8 Z8 G9 X$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
. I: J0 j# T/ S/ x. E  K
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
$ T) U' w" W9 k# J& q* ^3 i0 A: I+ s) B) [% O
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
: Y/ @5 X$ l$ _
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
! d, G( g0 k3 Z- h1 H+ o
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
. {7 d* d! ^, |5 T
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
5 }1 P/ c8 k! S* G. |2 P8 a
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

2 F! C9 S  O3 U7 m
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
: Y$ a7 h! m: D% V
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );5 Z/ ]# N- W6 V/ C8 \5 I  ?
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
2 z' M8 H; ^# E# [5 c! C( {7 z
mongodb还有很多函数可以用,如排序,统计等,请参考原文。" I& C/ L& N) m, e; o  t
' [, A2 o- T4 A. K$ o: z  y
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:: R5 h4 e  B& p0 |

  m) l  w7 \- xhttp://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions' l  T+ T2 K6 e
4 \0 U- Z) I* R
版本二:
. r2 ]* }* p+ g1 W/ {6 g' ]
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
" L/ q( N% W2 B
  1. use admin
复制代码
: R: x" p+ B! \, i2 B3 P
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
- f6 L  R4 O7 z
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

& V" j( a! R4 d9 i' g9 b
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

  l3 ]8 H/ d" p3 U; Q) D
         5. #删除用户
  1.           db.removeUser('name')
复制代码

6 B/ p1 A  N& l
         6. #查看所有用户
  1.           show users
复制代码

! Z( y. Z! M) |& E( B: }7 i
         7. #查看所有数据库
  1.           show dbs
复制代码
" j: G  ^& u9 n$ K+ Y8 \7 X
         8. #查看所有的collection
  1.           show collections
复制代码

9 e$ H; `; j& [& d: V7 }' Y( q
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
5 q8 t+ K' l+ E- P1 \
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

! c& b& L3 m4 n$ E7 _6 Q' ]
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
: Q, _% K. g4 a4 s6 V& K. Z
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

2 r* J/ `# @# x  D0 W. m
        13. #查看profiling
  1.           show profile
复制代码

( w9 F3 Q; a5 i9 r2 n2 |
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

: N, k5 H, x( g9 C/ r
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

0 K' j0 U! w4 P$ h$ ]5 _
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

1 r9 b- ~  z' c/ A/ S
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码

% m/ Y* e0 `& H
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

* r; U: h, D& C
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

- q; @$ {! P7 J/ J8 W9 @$ N" X1 u
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

4 e% b; u7 n2 V( J5 ?
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
& b) c' ^0 m; f( d
   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()

5 |/ O8 J. p0 I
6.  高级查询
条件操作符
1 ^9 V' [% m7 N: \
  1. $gt : >
    7 z" ?$ ^1 X; t8 K
  2. $lt : <
    9 k4 v: }% H. m4 `6 a
  3. $gte: >= : X/ }3 m! y+ I, B2 B. `! k0 r3 k1 L
  4. $lte: <= - G8 P: ^0 N$ d2 y" H+ V1 X
  5. $ne : !=、<>   h4 j$ e1 }0 _( D  B$ f; x2 m, J4 W: ~
  6. $in : in * u: k' V2 [. x3 @7 S
  7. $nin: not in
    ( n7 j: Q7 [! i9 A) O5 Y- p" J
  8. $all: all
    $ R+ U+ Y% H: j4 Z' ^: e' t- ]3 a) |! g5 H
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

. j/ i2 `- [% c6 {0 w+ M2 M& B) M2 U) O5 }2 ]% N5 Y9 q! x5 k
查询 name <> "bruce" and age >= 18 的数据
5 ^6 b9 R1 z# }
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

/ `$ S9 ]+ m" |2 d' i2 n
+ j( w* i; ^' f2 P, t3 B, V查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 ) f- }2 v4 @+ E3 }- q# O/ `% u
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
. Y3 z6 }( I% I6 V$ g4 a
& T! d$ R2 G# E
查询 age in (20,22,24,26) 的数据 $ a4 w, M! X" ^
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

6 [) j* O5 b7 ~' k% k4 E
% [1 Z) M2 R" \. k4 ~查询 age取模10等于0 的数据 ! ?. `, u1 g0 m* J: n& r" I
  1. db.users.find('this.age % 10 == 0');
复制代码

# M2 o5 o# N# B4 q5 s: T8 Y0 r" c2 |或者
0 I! U' h# d" q+ }2 O) A" X4 y3 q
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

( J% i( q  l( l9 `" }- C; Z' c; ?8 B) A6 h) V( l9 I* W7 U
匹配所有
5 M2 l0 m& M/ G  O& x9 Z  c
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
/ B# \6 e7 D2 I% C( `3 C
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
  h7 w; i. L( i) h5 M! S) o) f# U. _可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } ! p1 A; p: i4 q# \) j& h, ]  j
* R( _  _+ b2 z* Q: ~
查询不匹配name=B*带头的记录
& _& H2 S7 G8 H; ]! u) ~* I* Q
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

! p# U$ V/ g8 x3 Z+ X$ Z: J5 w查询 age取模10不等于0 的数据
4 l6 ?  n( ^* \1 d. o+ j0 |, i6 J! n
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

$ ^+ u$ F' I7 S' z& L9 H  u
: w' I. W& E7 x" R1 ^" s#返回部分字段 5 ]" M$ A3 V5 |% F6 n( L  Y
选择返回age和_id字段(_id字段总是会被返回) ! q9 k1 Z+ e8 {; [; \' W3 g# W) z/ z
  1. db.users.find({}, {age:1});   Z2 E& v7 J; G9 d( b
  2. db.users.find({}, {age:3});
    7 P$ i8 h0 n5 m- r/ S0 B
  3. db.users.find({}, {age:true});
    / W1 R) ^  j( P; A5 v  X4 v
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码

( _' X. ?2 w: h5 o& O& O7 ^0为false, 非0为true 1 J( y4 a& P1 B8 Y
) c) q1 m( N" a# d4 v/ u% l
选择返回age、address和_id字段
5 Q  |9 ]  j$ c; U6 J/ S. Q4 V
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

2 B+ s+ [; i1 b! w
% [2 c  I1 E& i! w排除返回age、address和_id字段 2 E% b& c: @/ o, S, j
  1. db.users.find({}, {age:0, address:false}); # a& a  B# k9 a3 h! D- @9 F
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

7 i% n( g$ y; u: k5 \) V: H; k+ p* J
数组元素个数判断 $ t5 ^, j$ a$ g8 z5 U
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 1 C! P! t( S/ h* o9 R( }
匹配db.users.find({favorite_number: {$size: 3}});
7 m# ~5 {! `, e# J7 s  a0 A; }不匹配db.users.find({favorite_number: {$size: 2}}); " @  C8 S( Y# H2 u, v+ l

- S& t- E7 R6 d& n0 W- Z7 W- Q& T$exists判断字段是否存在
* I2 O4 I$ @2 n! _7 f* s- l+ w% o查询所有存在name字段的记录
, Z* ~: T" e9 p% y7 ~8 Z
  1. db.users.find({name: {$exists: true}});
复制代码

$ t$ S# O* X7 R  o8 V查询所有不存在phone字段的记录 $ S4 I" u3 A+ @0 b  r4 i6 s
  1. db.users.find({phone: {$exists: false}});
复制代码

" R4 t9 n0 J% L! ]+ \; ^/ C
6 B1 U" r' p& C* |% c$type判断字段类型 9 [# y7 T! R4 R( a8 ]
查询所有name字段是字符类型的
- v! N& D% ?2 {$ @% B0 x
  1. db.users.find({name: {$type: 2}});
    " Y" S2 E# i, Y6 M( K
复制代码

$ |; W$ a  ?8 Y5 c查询所有age字段是整型的
2 J9 \/ l' t; H6 I0 k2 y$ |
  1. db.users.find({age: {$type: 16}});
    6 p2 i  s/ r, p5 z+ s
复制代码

$ B1 \6 a; D) `: `4 V! ?对于字符字段,可以使用正则表达式
4 n' _! @& @3 m3 o* u* b查询以字母b或者B带头的所有记录 4 `. k- H# l* ]( @) X9 P
  1. db.users.find({name: /^b.*/i}); ' D$ ?6 z: g, f. a5 V
复制代码
/ M! z% I3 X' `8 B% V/ q
$elemMatch(1.3.1及以上版本) / e, p, w$ k# q0 @, y; H- D
为数组的字段中匹配其中某个元素
9 e7 d+ j  R% u, [( o9 M. N8 [' `) g* p* [3 m: ^
Javascript查询和$where查询 ( z; _, a# s8 r
查询 age > 18 的记录,以下查询都一样 $ Q8 m' f+ a9 L/ `3 B% K
  1. db.users.find({age: {$gt: 18}}); & `  {2 x# h/ v  j2 U3 g
  2. db.users.find({$where: "this.age > 18"});
    / D3 k2 G2 X) a- n- S! m6 U
  3. db.users.find("this.age > 18");
    # P2 t: k: y% \2 v/ D
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
3 X/ {; h" K# L3 |4 F$ o

% w5 K, S5 h; K- G, h) M排序sort() ' o7 e4 Z! V8 T5 w2 X& l4 o
以年龄升序asc
, |3 ^2 C: r  w' {
  1. db.users.find().sort({age: 1});
    ! j. h4 p# v  F
复制代码
) R8 `8 ]6 M& z4 h: w
以年龄降序desc
1 R3 R8 M$ a5 H" o, ~
  1. db.users.find().sort({age: -1}); , @3 ^+ I  ]& X4 m# ]
复制代码

  d0 v0 q: h7 Z) C5 e, `& Y5 ]* J限制返回记录数量limit()
" }: G1 q! |6 d. t; d1 W. h+ _1 s# U返回5条记录
1 ], I- p, u  M- f1 c0 ^0 k& F
  1. db.users.find().limit(5); & I. A& T: h, D, g' v% |
复制代码

1 v; q8 U, t4 p! |/ j% M返回3条记录并打印信息 6 s: L* v; z. B/ ~2 g0 |! @+ L* U! ~7 ?
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    3 j4 v$ Q- D2 v( t
复制代码
' O" m7 A% X0 A
结果 % Q8 c# B1 p7 B+ J/ m
  1. my age is 18 8 r, m" I. [: R7 v2 i
  2. my age is 19 8 z2 V7 a$ |% o6 u- ]; N1 I" T7 L
  3. my age is 20
复制代码
7 i( ]9 f4 O' t/ v$ @
, g/ B7 j$ d0 B( h4 w1 {
限制返回记录的开始点skip() 0 U1 P4 p) i6 P0 X9 D$ ^8 n6 u% A! W
从第3条记录开始,返回5条记录(limit 3, 5)
- X# a5 s8 L/ }9 h
  1. db.users.find().skip(3).limit(5);   @/ y; F7 i4 x; y9 t" r2 b5 C
复制代码
$ D8 Z8 c9 M/ B6 x% N
查询记录条数count()
9 w# m) H: Q; Ydb.users.find().count();
6 e% R$ `  P  H4 F5 U. X0 H7 Y# A* Mdb.users.find({age:18}).count();
* F0 _% A) y( h- [* c* @以下返回的不是5,而是user表中所有的记录数量 6 O6 `0 B. V% d5 ]
db.users.find().skip(10).limit(5).count(); + J8 ~- w0 S# ~' c, ~
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
7 d2 b) s# o# i; @3 o
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

0 u& d! `/ n' S8 g2 F9 E
2 U; ]  E7 N- `" Q& o8 A分组group()
. A8 {* z3 r) C# p假设test表只有以下一条数据 ) `$ C4 K1 y7 t5 L1 W" E/ {1 t
  1. { domain: "www.mongodb.org" 3 M) n2 R9 Y1 o# d& [9 ^
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    7 m( {6 j* w# @: _
  3. , response_time: 0.05
    $ \: i9 P7 L" K' P7 S
  4. , http_action: "GET /display/DOCS/Aggregation" ( a5 v- }9 z2 }9 T% D( r8 H
  5. }
复制代码
( ]: @0 }; p8 w* H
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; - d% J9 H+ e& ~  \# ^
  1. db.test.group( " x: X7 ~% s6 G) ^, n& Q! T
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    $ o- r0 P3 G0 h. e% t& K8 r
  3. , key: {http_action: true}
    3 A; Z5 A2 u3 l" u! l
  4. , initial: {count: 0, total_time:0}
    $ ]& d' Y: ]* R# `' M+ ^# t, e
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    & E& e7 ~" t" e  L! A1 t
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } ( `+ ]$ ~3 Q; t5 M$ ?
  7. } );
    9 E1 ^, Q2 g5 k8 k

  8. , J6 t3 W4 ]! Q
  9. [ + Z8 {" ?8 Z# D; q  U
  10. {
    / M9 j2 O8 I4 A3 _
  11. "http_action" : "GET /display/DOCS/Aggregation",
    ) ]5 d& a" N8 y
  12. "count" : 1, 4 r1 x# ^+ Y. o: r$ B8 T- F' |% W
  13. "total_time" : 0.05,
    / a& g* O1 \: u" x
  14. "avg_time" : 0.05
    8 r: n, D. Y6 |+ ?
  15. }
    & Z: Y, O: {& Y$ x/ h
  16. ]
复制代码

% X. I9 Z: |) }3 q2 B9 A4 F# \
2 C2 R( x/ \/ L0 C. b3 L, M( k2 ?- R4 k$ {. n2 l6 f
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 a' R) v, I! W. i! ?# v+ e
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

) v2 ~$ ~* ^. T6 T/ `' Y. o9 I+ Z# m. J
- n, I; a$ Y; A  a( c  H% c/ L4 I. h
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct
    2 C# ?0 e8 v8 e* f
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码

4 g0 ]( Z6 B' Y! r
  l. _. K2 }4 v( S. {" M
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

+ `, o' v$ K5 D4 s% N, H( N! h2 E  }$ J, x, x7 R4 m1 @* S
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
2 M. Q3 f/ f9 [% j' s$ J# X5 p
5 ~  s5 N0 S2 I0 {5 G) ~6 T+ t$ j
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

: x6 _2 w* \  ?3 q
$ b; P! M2 ?; b  a& J, g4 L
输出如:
  1.           q  T9 U( H1 M+ B0 F( b7 H
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

7 d9 j; Y3 J0 u  E/ K. C, ^$ ^0 a6 y1 |. o# \% ]
: j* P6 C; ~+ l& L# V
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"
    # h& X& Y$ a, Y& U7 A# z
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/ O/ u$ c* c- ]9 T
  3.        xmlns:context="http://www.springframework.org/schema/context". C3 m. W( y/ {3 O' F. u
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    ; m$ o4 i/ }/ Z5 g* E+ E1 D! x; A- |4 ~
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans, B2 q- ~  P4 {' `- M
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    - R, S8 U9 u- t! u$ j
  7.           http://www.springframework.org/schema/context
    , J* c/ N5 F9 H- L
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    , I% }5 w6 M/ Q
  9.           http://www.springframework.org/schema/data/mongo: S! [/ f! R9 L. c( e0 Q7 h7 v& h
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    ) l' `" C, y  K8 z! E; ?

  11. * R7 F) M8 [1 [. Q3 w& o
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    ' t' `! v' C! e. ~' t" Z' @  Z: O
  13. " P) u1 I: z" t
  14.     <!-- Default bean name is 'mongo' -->
    3 E; O- Q0 R5 v. m
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />, I4 v1 R# S' J9 O" L

  16. 6 J/ z4 y- j8 k
  17.     <mongo:db-factory id="mongoDbFactory"
    6 O3 B, c2 B. `  r1 T9 u8 M1 F
  18.                   mongo-ref="mongo"& t$ L+ M. E5 ~' I
  19.                   dbname="mongotest" />( P8 {" d- r) d" {$ n! J7 ^3 e
  20. - b" h2 L; V8 B. b! x$ x" e
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    1 E. c( i; n4 I0 L& F- S
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    ; q$ v8 n3 E3 h" v
  23.     </bean>
    ! L' p7 h& H- w4 i3 P$ ^% j
  24. </beans>
复制代码

5 `8 y3 m' q0 [6 t

. Z$ F2 ]% a% W( C+ i/ X
maxmin的测试
  1. @Test1 E6 [6 g. e. h8 t
  2.     public void testMaxAndMinAge() throws Exception {. ~9 i8 A* b8 C* B; n
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
      h# D# t7 }+ T. x) |! m! d* z
  4.         Person result = mongoTemplate.findOne(q, Person.class);
    5 E. B2 o0 E. z! Q
  5.         log.info(result);- ?! R' ^1 z4 I: \
  6. 5 C2 _# _( {: \& H& A
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    ; K5 n8 R- H2 Q+ @6 f
  8.         result = mongoTemplate.findOne(q, Person.class);
    ; [8 T9 r/ P- x7 N+ M$ a
  9.         log.info(result);4 p3 [, {0 y) \
  10.     }
复制代码
& a9 S: ~2 j2 @$ k& u
. Q+ u& J6 r/ z, U5 Z4 C# b+ ]
distinct的测试:
  1. @Test3 }) t! n. r5 R% F4 D
  2.     public void testDistinct() throws Exception {
    4 D0 O9 r) Y1 d- r
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");& g3 R2 v; h8 p/ x" D3 x/ _+ H
  4.         for (Object o : result) {/ Z- Z% G7 N& w8 g
  5.             log.info(o);
    ; R5 ~0 `8 S7 b3 S7 m
  6.         }
    6 V) ^4 B" t7 U! b
  7. , }3 O8 y3 u! h" l' W- m0 ^
  8.         log.info("==================================================================");
    3 d- _  |) _' p1 D0 j; q+ Z' C
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    / M, i" I& z1 V
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());- p2 _" t- }6 @
  11.         for (Object o : result) {& c; R  T; e8 ?
  12.             log.info(o);
    , |( f$ u; d) j* ~5 S
  13.         }
    , |9 e$ Q. ^9 A' F8 p" q3 Q

  14. ' U9 Z6 ^4 `3 t
  15.         log.info("==================================================================");
    # \4 H! X8 p; j6 L4 D) V9 A
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");0 n, M1 q- O) e: v  N6 H
  17.         for (Object o : result) {
    2 U8 N! E: b* A7 m8 R
  18.             log.info(o);0 i. _: Y) y4 G: T  X; d% J0 {
  19.         }! h( e0 }3 A/ |) R9 ?
  20.     }
复制代码

8 i1 g! X0 d" M. U0 }; T; s: k* h8 f5 t
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567, d9 O  m4 u3 {
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    $ [0 u9 i5 Z4 _
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789, p& B0 Q/ S6 t7 x4 i
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654; I$ w+ X7 s* E4 [' Y7 y0 v: }
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni3 N+ a. x3 k% }- B* M2 ~
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    7 O. ]/ z  r" u# J  d# _5 \
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    , Z* |4 t& n5 \) q. Z
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    ) t% ~! x6 I; B$ ]) M
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567: l: g3 ?# J, n  D) C
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 3456787 X& A' k+ ~' f2 b3 \" F+ }
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789" h' |( g  l4 K% N( d* i" e" T- A  ]
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    7 B% S1 o& W7 u4 B) v, n4 f& }
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    5 d4 x  \" u. R, ~& ]6 @' B1 L
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    4 _$ p9 y% s, L, l; v: G/ k
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    / w+ d' L7 x" O8 t, `
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc4 m' }  D5 X9 X% A  v
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    ( r+ N, Q  g7 o- m
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx1 q5 O5 O; O2 W1 N/ `9 f! T
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    $ {; q) H- c% v2 e2 R6 S& U* \( Q$ V- }
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    * d! `% s) ]0 |+ O! s2 X
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    1 P" T; Y* {9 h
  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
复制代码

8 o8 A- e% I5 c0 m# j" }$ q% W7 L% U
这里我要特别说明一下, 当使用了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等信息。

& L0 ^1 u2 v* e: r  Q2 V, @& d- n: C' i8 f1 p
! }) l, Q& L. p% _3 e8 h- `: z
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-7 21:36 , Processed in 0.137800 second(s), 24 queries .

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