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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:
, o; v# ^" I# v8 I& i
& a! W7 v6 T% X6 Q" J) |) E4 Y$ S1 ) . 大于,小于,大于或等于,小于或等于
5 V# y* Q6 f. i1 ^' j% @' e5 n- r6 p4 n5 {3 a; S
$gt:大于0 A4 l3 T: ^) Z8 |( h" X, J
$lt:小于
9 t7 I8 N. m# h$gte:大于或等于" A  P- o( d* k* r. h) V. I
$lte:小于或等于6 V# k6 j5 \8 b! P' e) |
' {9 f1 n/ v4 p2 G1 l: t0 E
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value% [  Z1 r' k; M' S5 Q; u
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    0 U- I$ u/ a4 ?& `9 X
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    # H4 n6 t# L4 S& }% Q% G) z; H: t
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
7 S  c4 ^4 O5 ^1 m: V; \
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});+ d. K0 g9 @+ r
  2. db.things.find({j : {$gte: 4}});
复制代码

0 ^; g: Y3 `  d3 l
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
# I3 j% \" h' ]
3 x- k+ ~7 N9 H. l

0 r3 M  |; a% B
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

( R9 D; N7 ^+ D0 W& N* Q
3) in 和 not in ($in $nin)# i# u4 t0 F1 h
" A; J1 ]% L+ h- j& L5 {$ ?, ]
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

( G# U: l' A) d: R- j
例子:
  1. db.things.find({j:{$in: [2,4,6]}});1 S3 P0 N& a$ O) D
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

( L9 X2 m/ ^' q( z/ Q7 h5 u

( o' A  I4 j0 j7 X( C& l4) 取模运算$mod0 d/ H; ~4 C0 s5 m! z! @( c

- {) j$ x0 Y0 a8 G! Y6 R如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
; v- D1 k; w  ]
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
4 o$ i3 e3 c! y; D3 a8 _0 a

  k+ D' }/ ~' i5)  $all' o( S* S$ w% c/ O# K5 T- t
3 a/ z/ ]) s' h2 Z6 Y- [3 J  u
$all和$in类似,但是他需要匹配条件内所有的值:4 Z' Q+ F8 _: G

1 Y  ]6 H; I  I如有一个对象:7 i5 V" w1 L/ b4 g7 g$ [
  1. { a: [ 1, 2, 3 ] }
复制代码

$ O- \$ E- q& |0 W
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
( m! j' h. s" V" c7 H8 A' r
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

( W; Q. i0 i1 p! P
( d2 f7 c; G: z8 ~2 s1 I
6)  $size
3 W* W  r2 I: s0 R3 J2 M$ J" @: R* ^
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:0 x- u' @6 r$ {

6 z( `$ ^( R: y4 E2 K5 A, W下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

% Q' Y7 w- p5 f- u, q1 U& d
官网上说不能用来匹配一个范围内的元素,如果想找$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 f  x: u* R0 b% i+ e/ u  s4 v2 z
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    ' F) S8 d0 S0 j/ G& L3 I! O4 h& a2 F
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
7 C$ N  g0 b, N. X; Q# O
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string9 O0 r, S0 Z! B: s: v4 I% M
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
) b: j( h( G9 ^2 f6 I  A
9)正则表达式  c+ ^2 q( _5 c. g

$ c: ]8 F# x4 i) x6 d, X+ qmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

, r" {0 ]7 d8 l6 t# q" g4 a
10)  查询数据内的值% p1 Q2 |$ v& o% e
8 F1 \+ _) a. A) q+ p7 a- S. |
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
5 V4 A7 G- d4 F5 a
11) $elemMatch
7 M7 K# O7 d. @3 S
7 k0 }& T  ~; y7 X) R$ C9 m3 d如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) " h( m, a* X- R0 G, k- i
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  , D' X7 Y/ R7 {& B5 b0 x! U( d
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    & `; o% l9 ?9 Q4 \# o
  4. }
复制代码

  M0 A3 @- {2 b8 P$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$ {2 \$ {3 h% y5 g6 t
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 3 L, I7 X# j6 l3 w& }

( h" c5 l, O. c& i5 [/ M& `12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码

* c( z% R# y; N2 I+ [+ f) n
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

! ]) E) x+ J& h3 P
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

" D/ v4 H0 n+ S% P6 C  F
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

) _* \9 C) y7 R( d: g
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
4 V5 _2 \2 j/ Q! d) Y+ n
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
$ I2 M; l' H) @- L0 u6 }4 Z
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );
    ! k, I+ N5 G9 k
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

) v- X0 K+ b) Z9 m
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
  M0 m! Z2 A& H: t, t$ d8 w1 m4 i# G
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
9 L4 p* |# g6 j2 X, s2 R) y( y8 I% \4 O2 H
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions: D( H% `. ~6 q7 ?. B3 F

1 K$ d( t# p2 y, E* v( Z版本二:$ Y4 u0 b( D. L2 e* ^
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

+ w0 b! O$ R" ?
  1. use admin
复制代码

: d! H+ l' t7 q9 j9 @
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码

: s# _7 \' ^. f0 z  s% b
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

# G, T6 u; D1 @. I  {
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
" O$ k4 l0 \2 J! o! Q
         5. #删除用户
  1.           db.removeUser('name')
复制代码

! [4 ~2 q5 n4 C! P+ d
         6. #查看所有用户
  1.           show users
复制代码

" R/ G0 i, [# V$ \
         7. #查看所有数据库
  1.           show dbs
复制代码
( r! R: G/ B* q# f
         8. #查看所有的collection
  1.           show collections
复制代码

' R+ }  j8 [8 C( O1 x7 M( C
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

* h+ R, S. x7 h) z' H* k) L# ]* E: X
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
$ v7 ^$ u7 w6 ?8 g9 C7 Y, V: A
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

& Z% F( A$ b( Q/ R, ?
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

2 u5 x  t* ^8 \0 P
        13. #查看profiling
  1.           show profile
复制代码
3 r& ]# h4 @4 O3 M# o4 \
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
1 L( i5 h# l' H% g2 N4 J/ }0 e
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

5 U* t8 N" y% K/ z; T
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
9 J* K3 O  D- P% M' p5 n0 e
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
) d, p/ c3 h9 T7 a+ }& C% K9 U
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

3 u7 y- X- Z' X3 \$ v
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
2 ?0 [% [0 C; s0 V' i
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

0 S9 T6 }+ H8 x& s9 v
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

' F+ {7 k# T* L4 t# p
   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()
7 i4 p4 i: h4 L
6.  高级查询
条件操作符 - N8 ~6 t3 o5 p8 _/ X$ T
  1. $gt : >   D& F" z& Z+ M, i: a4 c2 |. t! m
  2. $lt : <
    : H7 h6 ?7 S7 g. E( a
  3. $gte: >=
    4 _7 G. x( y9 P
  4. $lte: <=
    " q# x+ ]" I1 ^
  5. $ne : !=、<>
    8 E3 f! N  J) v# I- _
  6. $in : in * e" q: _: n" p0 I7 n
  7. $nin: not in ; K; L6 R9 B; a! y* w
  8. $all: all : S( z  T$ s! |  D
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
9 r, Z4 q: G! x) S& w8 Q

/ N0 z$ W% ^$ Z( x7 {* z- _9 s查询 name <> "bruce" and age >= 18 的数据
/ r! V2 b& f% q6 A
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

; K7 \" C0 x/ K/ p, ~
/ X; L' q/ w1 ^1 S+ e" t0 Y查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 & p1 ]5 Q  s  v8 ^
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

" n  u; {  k  t* A; ]% m# i" n* V+ O  u
查询 age in (20,22,24,26) 的数据
( W; t6 R' V1 s  G: y' H5 G7 s
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

6 o: r* X: y! j; ?: V0 Y; z( p  N) P! Z6 z/ L+ @/ v
查询 age取模10等于0 的数据
9 I- t4 Z- `5 S- z) V/ g- ~; c
  1. db.users.find('this.age % 10 == 0');
复制代码
! r  W; g9 H. Z! j5 \0 C6 L
或者 ) W; P+ d' d! c2 g& v4 v6 v4 N4 R
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

7 U. v* R: t9 x" G3 Z
/ `0 _0 I# @' m0 i匹配所有
- {+ q9 ~7 @# r, U. [4 T. H
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
' N7 ^& C  `4 b1 Z' Z- w$ n
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 8 \: B* ?6 S  J6 H
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } 5 k4 c0 r& O+ k/ v3 k2 r

9 R0 o4 F/ M$ _查询不匹配name=B*带头的记录 * i8 x9 K( \: v
  1. db.users.find({name: {$not: /^B.*/}});
复制代码
, }5 i8 w7 ~" f. g
查询 age取模10不等于0 的数据
+ B6 {' h9 i  I  C* r
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

! d9 W) g8 N: Y/ X3 d* A
# e8 T4 b2 D) g/ B#返回部分字段 9 I; P: x4 L* K: B% l
选择返回age和_id字段(_id字段总是会被返回)
0 Z3 X1 P9 N+ h- B+ \* N
  1. db.users.find({}, {age:1});
    ! N) Z* [1 U" g- Y
  2. db.users.find({}, {age:3});
    2 {5 F" ?2 G: I2 O3 M
  3. db.users.find({}, {age:true});
    + L# k4 U, n0 |8 J6 P/ r
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
  J2 b0 I' V$ z
0为false, 非0为true
; V3 m0 w. R1 o
) O9 j' ]5 j- T$ D选择返回age、address和_id字段   ^% C* `9 a& a2 s% Z( ]
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

4 q/ H. v! K9 d; ^4 \1 D6 z8 V$ ?* U8 r& [) r
排除返回age、address和_id字段 : h9 f5 j  g, Q& r1 H
  1. db.users.find({}, {age:0, address:false}); 7 O# w  ~1 ^8 u
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
  R2 s1 k. C. Z' g2 q
, ~, z' z- f4 C
数组元素个数判断
% A% N9 r% ]- H# t0 n对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 4 Z7 I# C3 A3 n2 Z6 s! A' P$ e  O3 }
匹配db.users.find({favorite_number: {$size: 3}});
$ y2 `  ?$ M0 Y& P! M不匹配db.users.find({favorite_number: {$size: 2}});
0 f6 \: X1 w5 L+ P, N8 ^& J9 I; p
$exists判断字段是否存在 . k) e/ F4 Z3 w9 \5 s6 @
查询所有存在name字段的记录 9 j; A: m: x: S. ]
  1. db.users.find({name: {$exists: true}});
复制代码

5 n" k# C  Z) q$ r- M查询所有不存在phone字段的记录 ' n+ h' U5 o0 R& R7 _* |) {
  1. db.users.find({phone: {$exists: false}});
复制代码
; f+ q5 M; B" g- |
0 W! D% ~/ p% @: P7 R0 n8 v- M
$type判断字段类型
- p4 h3 j) k0 N. X! l查询所有name字段是字符类型的
' E( C4 |; U! f, R1 D
  1. db.users.find({name: {$type: 2}});
    3 S2 x* B! v6 x. g4 r3 Q
复制代码

+ |$ V$ N  T/ }. A3 ~+ k查询所有age字段是整型的
8 {2 p1 N1 o! M5 F* R5 r# w
  1. db.users.find({age: {$type: 16}});
    2 l# E$ Z1 z# b+ l  N5 `
复制代码

9 `; B0 v7 ^8 e. Y2 m对于字符字段,可以使用正则表达式 ! n5 l5 z5 [0 v6 x( x( w7 X( K* g: o7 W
查询以字母b或者B带头的所有记录 ; O7 @; t/ [4 C4 S! A2 |9 y( v
  1. db.users.find({name: /^b.*/i});
    2 S& j: J5 d5 z8 c8 J* |8 W
复制代码

. R  N6 `# R: `! J$elemMatch(1.3.1及以上版本) 3 Q$ P$ T! w/ r" C  m: U
为数组的字段中匹配其中某个元素 9 {( `: X: H' `: S; M0 T, R

2 h+ H. x# B: }, s8 S% MJavascript查询和$where查询
' h; @4 ?. k% O$ U% B( n查询 age > 18 的记录,以下查询都一样   y2 y' \. c% j' E
  1. db.users.find({age: {$gt: 18}}); 1 T: t% A/ ?! j% T$ X8 `. U
  2. db.users.find({$where: "this.age > 18"});
    9 Q7 L& \3 ?- {0 Z/ T# ?' m
  3. db.users.find("this.age > 18"); - j0 ^! I9 N6 t7 G  |" V5 e
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

6 K. o  X( S5 v  T; Q  Y( q2 f/ \2 t3 X8 \" [# d5 {  C9 v
排序sort() ) M$ M2 H( z0 ?" A
以年龄升序asc
2 L- ~) v6 |# i$ H
  1. db.users.find().sort({age: 1});
    , o) ]" I/ o. J4 j& g, p
复制代码

. d2 o0 x" Y& V, t$ h2 A& T) |以年龄降序desc 0 N% f( J! Y5 {0 D
  1. db.users.find().sort({age: -1}); $ w5 R0 B9 l- ^/ [5 X
复制代码
8 @3 s9 D) O2 @6 i4 N7 Q
限制返回记录数量limit()
2 B; o9 y4 I5 v" m" ?' w. q/ C7 {返回5条记录
* O+ ~0 z& Z) z7 J
  1. db.users.find().limit(5);
    . Y% e" A/ r" h- m2 f' i) O" F
复制代码

/ o7 @. Y( k. ?, }返回3条记录并打印信息
: N5 a7 ^/ o7 n1 g+ k! b5 c
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); . C  M1 ^- k* H/ ~6 s4 j2 W
复制代码
' I- F- Z7 |0 d. n: Q* |- P
结果 ' `; i9 s9 Y. B% v+ u
  1. my age is 18
    / V5 f3 L; o' v5 R* Z1 {2 |, P
  2. my age is 19
    * H, g/ p3 Y4 A8 u
  3. my age is 20
复制代码
/ [, K; f, c& `2 W: ~
/ n& G4 g7 t6 T4 Z
限制返回记录的开始点skip() - [  k) |( u$ d# ~7 U& T
从第3条记录开始,返回5条记录(limit 3, 5) ; s: r, I0 R/ n
  1. db.users.find().skip(3).limit(5); " G/ E) I  p1 x9 F
复制代码
/ c! S3 ^. R  s, u
查询记录条数count() 4 }8 Z5 `8 }9 V1 Y: e/ _
db.users.find().count();
* L' g( d. ^6 W: q" [/ r2 g4 w/ ydb.users.find({age:18}).count(); . l$ y# z: @8 Q+ H
以下返回的不是5,而是user表中所有的记录数量 / G: z: K5 s# B3 s
db.users.find().skip(10).limit(5).count();
+ {4 c2 v$ X4 y2 E. p' _; M如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
6 K0 v1 h; A! ]- _# E1 }) W! I
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
6 g$ o7 T: \: [6 N) |5 \# Z1 D
5 |1 `1 V/ K% b8 E
分组group()
3 c8 n" |$ Y, v6 p$ H! R8 o+ C假设test表只有以下一条数据 7 j* q# d; L4 U* d( |
  1. { domain: "www.mongodb.org" # \1 M, P: u/ M
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    $ [. @; J0 B. S, `& \. s
  3. , response_time: 0.05 3 C* G/ G! |# {
  4. , http_action: "GET /display/DOCS/Aggregation" / o+ K5 M) b2 A! G  H5 R6 D# K, @2 E
  5. }
复制代码
+ o" y8 E1 Q, H
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
% k0 z2 |$ i; p1 ?
  1. db.test.group( 6 P8 t% w. k6 \( u
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    / Y/ k2 A7 o3 Y) c
  3. , key: {http_action: true} % \3 |; }+ S7 a: ^
  4. , initial: {count: 0, total_time:0}
      j+ [; e0 q' Q5 d' q, ]/ f
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } : f0 o0 l1 U& ]: d8 z& P9 |6 A+ f2 I
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } . X6 ]: D+ e7 ^# T
  7. } );
    1 m7 T# s* `/ t3 T3 H% N- p

  8. : g, |) {' W# Y& g
  9. [ 6 J/ N7 q0 t( L2 Y% {
  10. { 3 C8 }1 ]/ g' V1 `! }
  11. "http_action" : "GET /display/DOCS/Aggregation",
    * k% i- d: \) W3 T/ G% d  ^6 a
  12. "count" : 1,
    & Z2 S4 ~) u+ [
  13. "total_time" : 0.05, 9 {/ k* g( E& ]7 i' E! G+ a8 |$ }
  14. "avg_time" : 0.05
    / q# d+ i+ h; B
  15. }
    9 R+ Y) W8 c3 [! Z: ^$ x4 f
  16. ]
复制代码

* H$ D$ k3 r. v# p- F- T2 A) Z0 b) U+ ^6 d: m

" i. N; y$ B% }$ [" [: iMongoDB 高级聚合查询
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( Y- W( G+ M$ K& X5 z
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
. T) f* Q0 r5 m/ ~- E- \

8 h2 A2 U  F6 g3 L, J
+ b; B& v9 u2 d/ B! r
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct7 m/ y4 L7 b0 i) t2 v
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
" E9 P% I0 Y1 t$ z0 V5 c0 s

% m$ O1 g: ]2 k& `3 I  P! o
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

; S9 D2 D" u8 E2 I4 j* o2 b# [! @2 [0 }* s
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
) O$ l# Z1 {: i

8 h2 {/ a% K# Q6 p
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
  L+ \: i& \$ w1 v$ [

% ^+ D5 M2 {8 _- _5 Z
输出如:
  1.         6 c& p- R! K0 r9 z% v7 d3 P. [8 E
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

7 @* z1 \# ?! L
: R  c) P% W  D
, _, e0 G' \, u$ w5 N/ M% ], e* h
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans", {7 m5 W0 b; J( ~0 u  g9 w
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5 ]! K8 }% C- p: P
  3.        xmlns:context="http://www.springframework.org/schema/context"
    ! o# B9 ^3 j/ Z! ~8 F1 O
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    : Z0 O; C# L- G
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans' r: U) |3 f( b
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    / _$ C. ~( p/ v$ e( I$ @5 g
  7.           http://www.springframework.org/schema/context8 Z5 B: Q9 P" \  Z7 f; a
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    0 v5 p! X8 u! u$ N6 W
  9.           http://www.springframework.org/schema/data/mongo
    ' Z7 w7 ]9 {- U0 G" f' N8 @
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">) q( i4 y4 X# u  P

  11. % w1 x6 p" Y4 x4 ]
  12.     <context:property-placeholder location="classpath:mongo.properties" />! H# x: m2 Y/ X* j6 l; F% A& q, ^& \2 T
  13. 8 ]6 L6 {) i2 O) x( C* Z
  14.     <!-- Default bean name is 'mongo' -->- z; y9 h; v! z" i" R; A
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    . M. b; X& w; l" O& J

  16. ) W9 Z' {0 O8 f! q* C7 R
  17.     <mongo:db-factory id="mongoDbFactory"
    3 {& Z1 |  Q7 H
  18.                   mongo-ref="mongo"
    3 R! P/ g9 `/ O
  19.                   dbname="mongotest" />
    4 t1 V# T* Z# n8 O4 j1 e) ^, c

  20. 8 s+ g2 v$ f9 y
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    + U" f- J- F+ D9 T
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    6 B- Q0 f# u4 T3 ?& o( E0 H
  23.     </bean>
    5 j* W+ y9 b, n1 Z; `
  24. </beans>
复制代码
, W% J; b% y+ x& Y' E

1 U( ^  {' o2 a5 p, \$ U
maxmin的测试
  1. @Test
    * _' O8 A9 C' {! s+ Y& i
  2.     public void testMaxAndMinAge() throws Exception {9 p& n" @( \# `$ a0 u
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
      `- n( l# _" S# ?
  4.         Person result = mongoTemplate.findOne(q, Person.class);+ h7 i' G+ u  i
  5.         log.info(result);
    % _' W5 M* t; x

  6. # u7 x9 B) o/ F* B
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);1 H( R. O0 ?3 `
  8.         result = mongoTemplate.findOne(q, Person.class);3 d( C5 D. X- o; w: D3 I( ]
  9.         log.info(result);. D; n( @0 K: C" t% M  W) P" ]1 ^
  10.     }
复制代码

8 m# c  T$ I) J" T
- Z( d$ U. w/ f6 S$ [
distinct的测试:
  1. @Test, ^+ k, S/ a* j4 X/ E- E
  2.     public void testDistinct() throws Exception {  b/ D+ o6 N9 {; Q, A
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    4 f  Z0 x" p" l& {& e( T/ b% R
  4.         for (Object o : result) {: |  D4 j: k* A- k  m
  5.             log.info(o);
    ! B) z0 _+ F2 f+ s9 S2 _
  6.         }
    ) g3 [+ y1 C6 S0 M
  7. , B( f: `7 v" v7 B2 l
  8.         log.info("==================================================================");
    & C) d/ [6 Q$ i0 P8 P
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    2 B7 K3 G2 k1 k7 q% \% k
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    ; W' }" I5 r( C, s+ B& k
  11.         for (Object o : result) {
    ( i/ c& g& u$ X: O$ n1 Z+ p  e
  12.             log.info(o);
    , s" t" {. D/ [. w8 c6 T7 u
  13.         }1 a" [6 J: s9 ?" D0 k" S# x  W
  14. 9 O% O; F! S7 k5 T
  15.         log.info("==================================================================");$ ]9 Z* Q! f" X& ?7 g
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");  }# V( `$ s9 I$ h9 N
  17.         for (Object o : result) {
    0 b! ?! Q& T9 F  D$ C0 U: A
  18.             log.info(o);) Y! r( q* u! D- S8 A- w
  19.         }8 u/ X# E& ?  f# M& [( d
  20.     }
复制代码

. a5 P! y! F! H2 d
' L" o7 {9 I! s8 N
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567# A7 f: c) o; _2 l4 r  |" ^, o
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 3456784 s- P3 ^; o, L6 ]: ?
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    - p6 t) D) D1 z0 l1 f7 s
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 9876548 e# k& G" E% ]- ?" [
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    & k" }: y; e! a' b0 q$ V' T. H
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo: j9 o- ]' c# o6 d& T4 [
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456  n% i* _% y- {4 q. ~1 a
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    # L/ ^. e$ s4 o* Z
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567! ^% f! Z5 S3 P6 V: t/ u5 K) K
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 3456784 p' s) ]1 J' Z
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    . j& M. y$ T1 a0 w" t
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654; |( J( _/ ]: p5 Z- v
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    % `8 N$ _# ^$ m! V
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa! `; b0 d: B# Y( D: r$ k
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb6 |7 R3 j1 m  I3 i) g- t! J
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    / t" `+ s6 F0 ^4 G# D% R- r
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    + {0 _- F9 r# N2 t# s) G" |+ h
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    & ^1 A2 \; c4 O
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    # I* H7 O$ t2 R8 m( ?, @7 F
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    6 u7 W1 a6 d2 z4 S
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    + s5 S4 Q3 {1 p0 e' f, o
  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
复制代码
2 c5 P- F% B. g3 k; c
9 U4 ~. \- q0 ]  [4 w3 N/ O
这里我要特别说明一下, 当使用了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等信息。

2 m4 A& S5 {1 `; [  B' U" e" c; \' x7 u/ F  ~, z, T

' m$ D" t/ F+ ]: A$ `7 z* a/ N
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-3-16 13:34 , Processed in 0.070139 second(s), 22 queries .

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