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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:& t! }4 ]; v8 o  ?3 `- S* Y
: j! \) d4 u* X2 d& l
1 ) . 大于,小于,大于或等于,小于或等于
/ ^  S. i2 G3 O: S0 K
- f! H0 [, U: j/ s* d5 z" I9 u$gt:大于
" t  ^8 t3 p  h$lt:小于/ z5 a& e) X  A) d* D, {  Y
$gte:大于或等于
/ E8 i+ g8 U; @$lte:小于或等于
" i: f; f- h: `( g4 j
* {1 ^8 K' [" z$ |2 U3 Q/ ?' v+ h例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value* t- Q0 G" F  \: p2 o7 {9 w
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value7 O; U3 L8 \  Z4 D+ p: Z& |9 m
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    9 @( `; c& T, T5 l
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
4 c' E0 V; P9 Y0 f- T# r# F
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});3 A" I4 F! D. ~  T1 X
  2. db.things.find({j : {$gte: 4}});
复制代码

# D4 ~; u2 E( E
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

0 U3 b( l1 [  ?# f4 i. B
% H, e- C- y  d  e) b) P$ D2 E3 u$ K5 O; B) m
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
6 L: e3 j9 W# {1 F  ]2 d
3) in 和 not in ($in $nin)
1 \' B0 T. t; z2 U+ {8 T8 e4 ?
8 Y$ ?+ U) |+ o: T4 K' ]语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
  U3 V5 u! T! q
例子:
  1. db.things.find({j:{$in: [2,4,6]}});- _2 P/ d/ w& W/ b; W
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

) o/ W8 z  A; i; ^
4 x9 n& |$ ]2 x5 V
4) 取模运算$mod' K! g9 Z0 B- V, E& C% ?8 R+ O0 e6 J1 h
; q9 y, J: ^" a
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

; }- |' [1 p- O, P2 p6 O  U
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

4 n# Z. f. A& |1 h) a: ^( F
" T3 Y/ w5 p! C' D1 L
5)  $all
* Y, m. G% h1 N
/ o4 q1 U+ i* M5 n# f5 Q( i$all和$in类似,但是他需要匹配条件内所有的值:
  O7 {7 c, h! B1 |) a
0 S$ y% m, @+ X& x' O如有一个对象:2 i: ]6 e  U8 _
  1. { a: [ 1, 2, 3 ] }
复制代码
, C1 @5 i$ J8 N; w1 p- q% b
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

) S* B9 d3 ]& b, [) ]
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
# a4 y' T4 V' s0 m: h- T
- P1 `3 b# W5 W5 @5 o6 R; N8 H
6)  $size
) Q' q) J6 t6 _9 `
; d3 C6 r* Q) c8 @' N$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:& A2 D' }0 \8 j5 o; u

6 ?  q2 }  B$ o' l  r7 [. l下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
6 h3 h: H# N4 r
官网上说不能用来匹配一个范围内的元素,如果想找$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.

0 S% d* A3 ^& R9 e
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回0 M+ g0 d, K# R1 {/ b8 V8 W4 K
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
- p7 X2 w7 o2 W. s9 [' L
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    / ~5 t+ f5 o  o
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
# [, P, x( ^' A2 V
9)正则表达式
3 W- l/ \4 O. D: k( T8 e* |# J- ~& n( W" x& G% h$ z! q
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
9 }; F' Q1 ^% _. D2 D
10)  查询数据内的值$ ?- Z! ^4 [/ {: p

: L1 S' ]8 B* ~7 J8 A% |下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

/ d2 v6 L3 v  k+ A/ G$ H- S
11) $elemMatch
/ v9 o& m6 O9 q5 _) a% E  j$ ]
; l- d: Q% r* F如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    * |3 r9 K( ]& x7 ?
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    ! q  }3 r* Z, d' ~# |
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]; S/ [$ F4 ?/ \$ L/ @
  4. }
复制代码

- u8 q. D4 p3 l$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )0 E; R- {, c. h- g. F
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 0 u' B% [9 I' p) a5 b( y3 F! ~
7 U4 B9 z% E9 R& ]
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
5 i& O, c$ \$ e/ d/ D
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
5 m# r  E! R7 ^! l
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
8 M# b- [: s! h1 K
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

* |1 |5 |# P0 P9 A, v- m2 L
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
" B' P5 s, }& N7 B
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
9 }) a$ f' p5 o1 x" ^
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );
    . W6 D8 G; i; ?& v. t
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
% D  r0 V' c# ^' {9 [3 y
mongodb还有很多函数可以用,如排序,统计等,请参考原文。' C  q# K( M! c6 U* |

# u9 a- E/ h* r" U8 ]; R& m7 r- V1 |mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:7 W) |8 u; U! V" g

3 a: |9 V+ V$ d( Ihttp://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
* H' ~1 o! g# K4 f: N9 L* r
3 C* v1 F7 |+ Z/ h+ E' m; [版本二:
: `' H1 l* r/ \
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

& q  G) S/ H: }2 y6 C
  1. use admin
复制代码

5 G/ x% T0 M" i
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
. M8 ?) j/ X: c1 z# w# H% n6 o% w
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

- X5 G  y$ |2 o( v8 r4 l& }
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

$ D& W- b5 J$ F. r& d
         5. #删除用户
  1.           db.removeUser('name')
复制代码

1 l3 j9 Y# c+ N7 m& @7 ]
         6. #查看所有用户
  1.           show users
复制代码
8 J* }3 Y, Z4 i: X" N' P- r
         7. #查看所有数据库
  1.           show dbs
复制代码

; r% b1 k! O6 f5 b
         8. #查看所有的collection
  1.           show collections
复制代码
# p  [; y/ y: `9 T1 S( h
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

3 R2 X1 Z" D) }- J( K/ q5 ?
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

9 C; `( r" Z6 y' l
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

/ g) }. g8 V- P* J. [9 J9 {; M
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

3 Y: Z. f9 \/ o& C9 ~3 n
        13. #查看profiling
  1.           show profile
复制代码

3 q5 q. u: U6 l7 p: p# w
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
; z  _  b1 _6 A, p% `
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

7 t0 D; @8 ~  k: o+ {* @
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
# F5 |' ^; h5 l/ z
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
% [: c4 [/ u4 u3 c/ R6 |
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

) K6 ^5 r, [! g# J# w8 @5 Z# [
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

+ z8 d; ^" q. u7 G4 F
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

  T3 p7 d% E) g# w% F! _2 ~+ [* f
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
0 O6 T, o( p/ U2 m
   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()

/ W/ ^; o  O; W
6.  高级查询
条件操作符
& {- a1 a: ^  Q& l! Q; h& N$ O
  1. $gt : >
    ) z  y7 h- w" X, [! y0 w# L
  2. $lt : < " N! }: k  W+ e8 s, D
  3. $gte: >=
    # g% p# n; z5 t: m% H
  4. $lte: <=
    9 R4 j4 R( M0 v# H) q! b3 K
  5. $ne : !=、<> 6 ~/ F* x# x$ K
  6. $in : in
    ' d, i; w. `+ D0 C
  7. $nin: not in 0 e  a4 I  L! W% D! j' ^
  8. $all: all
    7 j3 H9 m/ Y0 r- }& p$ U2 R' j% Z
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

1 ]" T3 w/ B. H/ z6 U, S: e4 ^
9 w7 J' x6 X4 @2 |7 \查询 name <> "bruce" and age >= 18 的数据
8 t  L0 \1 V0 I7 x$ c$ I
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

( I: w5 p7 O' B& H0 o1 o5 j7 n- K) A6 `; Q- s: \
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 % M/ v% f8 a+ y' |% A+ J
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

7 j8 y% E& `$ A9 C- p, F* j; Z6 x4 c9 h
查询 age in (20,22,24,26) 的数据
1 f3 v/ P" ]+ g& ~3 m
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码
- y' _' y% \. t+ m2 |2 U7 a

$ O3 R, {: e0 q# a9 Z: J查询 age取模10等于0 的数据 3 O# b% L& u+ W; `7 r
  1. db.users.find('this.age % 10 == 0');
复制代码
( Q  A: @2 x) @1 v
或者
8 x4 d/ b7 X& d% w& G# |
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
6 Y+ X4 G! [. T! ?  Q0 H
8 G: i3 u( i8 k  }8 p
匹配所有 . w# E3 d( V$ `, d' [
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
7 S3 c1 A. `" s0 @( U
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
8 I+ x3 a; Z1 [7 V可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } 1 u% P. K2 A5 q) g

! w+ a. ]1 X, u. S* T: L查询不匹配name=B*带头的记录
2 y" i) v; V5 @2 u' O
  1. db.users.find({name: {$not: /^B.*/}});
复制代码
. p- K% @4 \' R1 Y" O0 y$ }
查询 age取模10不等于0 的数据
) [" u* V) d3 M: l( f
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

) p9 b3 s+ W/ O# N2 }
; E! t) ^. P: ^5 S. Z9 f( |#返回部分字段
' _) D! _$ n  s2 R6 |0 }. {选择返回age和_id字段(_id字段总是会被返回)
# A# Y6 ]4 T0 o( i8 g/ G5 u$ J& P
  1. db.users.find({}, {age:1});
    9 v0 o6 `" {& S; n) e8 }( L7 \# r# u
  2. db.users.find({}, {age:3});
    6 }) k2 l( J7 n3 z% s4 B
  3. db.users.find({}, {age:true});
    $ S( C) Z2 L2 W/ H; m+ R
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
  ]8 ?! E! I, A% ^, W4 B( |
0为false, 非0为true $ _  ^& q; e" U9 k* r# \) k

6 Y3 C" S$ y1 f5 t. O. v) {选择返回age、address和_id字段
. _% O- o" K/ v4 i# O6 }
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

0 L$ w7 z6 I' I0 P# Z8 {, t; r/ ~; ~: S8 m* d# |. h3 t! c" V
排除返回age、address和_id字段 - Z% v; B, G+ \- ~+ ^- F
  1. db.users.find({}, {age:0, address:false}); ! P& T4 g# t' F
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

, z( N) d1 r* p/ x) W" X) P. D  K, n1 }0 E4 o
数组元素个数判断
4 n* o% u1 x7 x  @# H+ f# B( ^: C5 `对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 / b& L$ S. T& o9 s/ I; U
匹配db.users.find({favorite_number: {$size: 3}});
  q- a# _8 b! h: K: A不匹配db.users.find({favorite_number: {$size: 2}}); 7 r8 S5 c0 A7 d& @
0 @& b; w" |' y% c% F
$exists判断字段是否存在 + t  C3 q9 E( k2 n
查询所有存在name字段的记录
  i+ H6 u( Q$ i9 }" `# p+ Q  {$ F
  1. db.users.find({name: {$exists: true}});
复制代码
; q) H7 J( `; H5 ]9 s, y
查询所有不存在phone字段的记录
' R* C$ N2 V- y& u$ x7 j% t
  1. db.users.find({phone: {$exists: false}});
复制代码
1 T, m! o) f  I; \  J
4 u5 K" _( C( Z8 v% w1 f4 N
$type判断字段类型
& ~* h5 ^: d: S. U查询所有name字段是字符类型的
4 Y+ Y* a1 Z$ o: i+ K# t
  1. db.users.find({name: {$type: 2}});
    $ J3 ]+ T3 |; @" X! ]3 e3 @
复制代码
1 l+ s: j( q( _& `  t
查询所有age字段是整型的
3 D' ~) X% _0 L/ R
  1. db.users.find({age: {$type: 16}}); 6 s! e7 [  v3 A2 v/ o
复制代码

4 B5 [- K/ W0 A对于字符字段,可以使用正则表达式
( U- s: l& T- [2 c查询以字母b或者B带头的所有记录 " I/ ^# h2 [; i6 ?
  1. db.users.find({name: /^b.*/i});
    % A/ g4 J+ g/ K$ D5 v( F2 A
复制代码

8 X' j: r2 m  s& _4 f- |% |$elemMatch(1.3.1及以上版本) % S2 u2 u) S- b
为数组的字段中匹配其中某个元素 : Q& Z' q( g$ h0 K

: c% _/ ~/ n4 C* B' v- c, AJavascript查询和$where查询
4 q: C. _/ V( d% U  q查询 age > 18 的记录,以下查询都一样 6 I3 F+ }5 b+ O$ D! J% P2 X7 V9 o6 @
  1. db.users.find({age: {$gt: 18}}); & [( @. Y0 x# b' J! R+ ^# o
  2. db.users.find({$where: "this.age > 18"}); / _! o  _3 M+ b' G: \* I5 F+ F
  3. db.users.find("this.age > 18");
    # C, \9 E/ z8 Z# `9 |) ?+ \
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
; x8 E' ?. K4 J" I
+ Z; `% G2 s1 F! e" i3 \  K
排序sort()
/ g1 M' m0 I% r2 D9 B以年龄升序asc
( {# x7 F, q. u* }
  1. db.users.find().sort({age: 1});
    9 h2 G4 J9 r+ Q- \
复制代码
$ \" U# @- |/ |; j. S
以年龄降序desc
, j/ m7 R1 ]: x$ o6 W; o
  1. db.users.find().sort({age: -1});
    & n3 j4 V# w" G! i' F
复制代码
% O+ \8 ~: r& ^( C9 e& E; }/ j8 Z& o
限制返回记录数量limit()
4 j( m: g0 q: N$ h2 O" B) |1 ^返回5条记录
7 e4 S( V% Z0 T% s' F3 |" k  \9 S$ n
  1. db.users.find().limit(5); " r6 c4 w6 H6 B% D5 {" j
复制代码
; x9 f, I8 ?8 R& `0 R1 C( ~, ]8 D
返回3条记录并打印信息 ( B' s& R* ^- A/ v7 d
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); , ~& d. C+ Q3 m% b1 N0 F4 O
复制代码
% f7 @2 i' U: M- Z
结果
3 M& A. H0 T) k* ~' \- H6 V6 F
  1. my age is 18
    1 `. w% z# g7 B$ X* y7 R/ c" e
  2. my age is 19
    0 c  ?) y0 m6 W$ n& i+ C
  3. my age is 20
复制代码
3 z; [' g& D5 A. E  K! ?

2 t2 }/ q. o, F8 H, d限制返回记录的开始点skip() ( r& j# a/ j# V
从第3条记录开始,返回5条记录(limit 3, 5)
1 q9 D4 t) h+ c, k8 o1 Q/ n/ D
  1. db.users.find().skip(3).limit(5); : i; p) f6 s6 U/ i8 j8 _
复制代码
; ]( }0 m( ~( h- _& X% ]$ a! z
查询记录条数count()
/ z( o) |7 n, }: y6 H. D4 vdb.users.find().count();
- Q% L$ O' B# ^; Ldb.users.find({age:18}).count(); ; k! h8 p  K8 y6 K* \
以下返回的不是5,而是user表中所有的记录数量
1 ?* b  w+ z. hdb.users.find().skip(10).limit(5).count(); : W+ ?: }0 @+ W# k' K' H
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)   f6 D" D3 k% X1 U
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

6 S% M2 s$ i/ n1 c- \0 V+ `( R
) u( V4 K& C/ V分组group() 9 o* h9 T# S8 Q2 t# r
假设test表只有以下一条数据 ( y/ n/ u2 A  U0 \; n
  1. { domain: "www.mongodb.org"
    & R: y; I  c7 c: {/ l
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    " x$ J2 Y% E6 F6 z' F6 {" q
  3. , response_time: 0.05
    : Q6 p8 y5 l2 t2 }3 e. O
  4. , http_action: "GET /display/DOCS/Aggregation"
    ( S3 j; W. r' Y  Y
  5. }
复制代码
7 q0 D9 o: c- B/ H! }9 d
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
+ W1 P( H( v" [0 F
  1. db.test.group( ( }8 @9 Y! I& s4 \: n
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} & e( p: s3 w! H$ K/ q% `, ?
  3. , key: {http_action: true} 6 t9 O3 R+ J8 |% R$ v% H) I/ b
  4. , initial: {count: 0, total_time:0} 2 A% n$ ~$ A" m: |; F  D
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } ( Q* a5 ?- M: o0 S; u
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    # c$ ?& _! ^  A6 ?# R+ z
  7. } ); 1 j2 F( k' E) j; [. }% o- ~# {

  8. 5 N1 R4 M! P- A' x
  9. [
    ; u9 l  K+ k+ @% i+ d/ A
  10. {
    ) z" _. I, X7 S  ~2 u
  11. "http_action" : "GET /display/DOCS/Aggregation",
    7 n, @1 y% F- s7 G* G7 ]
  12. "count" : 1,
    ' f2 w* Y, K. n$ u4 e0 E
  13. "total_time" : 0.05,
    3 ~9 D8 O4 X- u( [: r7 M7 S
  14. "avg_time" : 0.05 + I4 p9 |& q( S6 j" l3 O4 A
  15. } % u. ]+ e$ U6 y2 t* P
  16. ]
复制代码
8 X% w' N9 Z3 w# g7 G5 B

/ |, ^: D3 E6 M. T8 G
; |0 O8 j  U& w/ W: j, uMongoDB 高级聚合查询
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
    9 t: ^% V: [3 r6 R% M
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
8 m  o+ f& B% ?
6 y  i5 V+ v1 l5 b* x

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

* R6 a  K5 b- |5 [
9 D% b8 P& x6 g+ [+ z
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

, w: W5 b$ d9 G( r0 u! O  q+ I/ f$ c8 t5 b, P, {! A
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

# m7 D' e7 L0 K4 D
4 [/ F& }; r7 c! d; p
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
5 g9 f% U6 [$ o6 W. O# ~

: ^/ i6 d- {5 v3 f# |
输出如:
  1.         $ ]; Y" L, O+ F, Z( B
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
% ?8 Q7 r8 B* }
7 X+ k' T- F- i6 O8 ~

+ D6 U  a; Y3 [3 d2 F
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"
    + R& a, X, |, b/ U# h- m
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"& l& K& @" q' D1 j6 K: U; L% I7 f
  3.        xmlns:context="http://www.springframework.org/schema/context"4 S" b, e  C1 e( D, o
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo") {; O7 u6 e7 t' u) D& {5 u
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    8 ]+ m1 U" F! E2 q
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd) G/ V, C7 P+ b) ~- s3 J, p# s1 g
  7.           http://www.springframework.org/schema/context
    / p; E0 D1 ?2 O) y* Q' P" {
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd, _; ^+ n8 P4 N1 v1 b1 A7 d
  9.           http://www.springframework.org/schema/data/mongo/ I* T% t6 U& e: N
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    - m8 s" H* o3 L0 h0 |  ?7 r
  11.   T, Y6 ~- Z; e) y! D! u- m
  12.     <context:property-placeholder location="classpath:mongo.properties" />3 w- c- \; D' T

  13. % }% i  L( k  x
  14.     <!-- Default bean name is 'mongo' -->: B/ o) \4 z* q! Q& u2 c% y
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    * c2 @- J) d5 w2 {/ g0 w( m
  16. # F$ r0 Z6 v/ u* Y$ S* u
  17.     <mongo:db-factory id="mongoDbFactory"
    2 a9 N& ?4 |; l! m( n% J2 D; v& G1 ]
  18.                   mongo-ref="mongo"( m4 G7 r! D4 C9 L! C& S
  19.                   dbname="mongotest" /># |9 q; Q5 [3 ?/ E  p
  20. - g- ^0 m8 u. a7 F0 \1 O
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">/ h! H2 N+ R. C0 z
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>( y' ?  P( Q. P# Q& u( g4 B
  23.     </bean>& X7 C7 d) ^0 j- ~+ y! _3 M
  24. </beans>
复制代码

. b  i2 c0 l( }2 Q4 k( L4 F
) e5 w3 V& f+ r0 N
maxmin的测试
  1. @Test( l4 Z; e0 r7 H5 b' O2 _; g: a8 U( ~
  2.     public void testMaxAndMinAge() throws Exception {
    ) e2 E' T( V6 r4 k5 y
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    , J6 b- f1 a/ K4 l& f
  4.         Person result = mongoTemplate.findOne(q, Person.class);
    2 w. L; G2 X' l$ @. ?
  5.         log.info(result);5 r: _1 R* V( \# j! K8 z
  6. % f. _. z. b* x2 r& {3 f5 E
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    3 k! k- f/ j& N3 u- @7 R( X2 v1 }
  8.         result = mongoTemplate.findOne(q, Person.class);
    ) T2 \% y+ v9 o' |5 Q* \6 D
  9.         log.info(result);7 w, n0 N: n9 Y
  10.     }
复制代码

! V8 O: l7 m7 Q. V
0 R7 k2 `9 d9 {" ~6 O8 A
distinct的测试:
  1. @Test5 ]# A8 D( {5 p. t+ `6 h
  2.     public void testDistinct() throws Exception {& ^6 A$ |6 l2 |7 H/ L0 ?
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");2 n4 d& m' O7 l2 R& u. I# H
  4.         for (Object o : result) {9 J' x# o' a6 a% v9 ?6 J  `; _1 v7 G
  5.             log.info(o);6 |; c4 J) P; B, B% m8 o
  6.         }. s, N, x0 V$ F
  7. , ]" z# S" Q$ Y" a5 S" T* j& |$ @2 f
  8.         log.info("==================================================================");" U* L8 G  J. X- z& d2 j
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));' P: @  |( k" Z
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    : c) Z) q# M3 h3 h! m
  11.         for (Object o : result) {
    8 b' `) w6 ?, \; S0 W
  12.             log.info(o);
    , o- z  r+ a% ?4 d. {. {' M
  13.         }
    0 G) f2 `/ Z& m9 Y1 i3 Z( @4 M  e
  14. ( L2 X; s) X% q% @8 p! ]" f
  15.         log.info("==================================================================");4 D" Y$ I! g# y4 v7 ^
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");. R: o! a. u- j; P. W
  17.         for (Object o : result) {' ^- ~* m$ W/ p" I- N3 J6 C9 @
  18.             log.info(o);
    . \9 b" e' S0 A. j$ ]" P3 a: c
  19.         }
    ! W6 E9 r  B* h! J
  20.     }
复制代码
. }" h9 q1 W& r$ {7 M! n

, ^4 u- z* r! l0 N8 N% V- u
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567  ^  w- u' |, w9 A
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    # s; R5 ]% E7 Q
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789$ e, z# C. |: Q2 O" S
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 9876543 Z4 c2 I+ M5 w4 H4 _
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni8 O/ c( `% j: i) ?
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    4 y0 s1 f& m4 |# }& I
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    ! j, k9 J; P$ ?1 U. M; X7 P
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================9 q# e9 n7 |$ V  r% t
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 2345679 p$ ]: j- Q0 J8 o, W3 b& m
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    6 X3 r4 E2 v- w
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789$ F- A' k/ C! a0 X# ]
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    6 Q# M9 W2 ~/ H. p
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================0 Y7 \/ X7 L) `1 |+ \+ i5 X1 \
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    ; F. C7 a; x$ \
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    , r7 F. ]! O- M4 X5 W0 h2 t$ v- H
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    * ]7 b1 k# C* K- K( k5 U% S
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    3 a6 L' t  C1 T* e+ n% O" G. A+ s
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx( B7 K! ^; H$ G" u) F8 ~+ ]2 {* N+ r7 q
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy6 P* V- b  r- h7 ?6 _
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    ! m+ }! s: l5 c% n& j6 P: h
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr/ r/ E. v( R4 I. x9 \" E
  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
复制代码

$ o  S8 }+ N$ f- v  E& H
. P( Y* Y# h8 s* V  c% 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等信息。

2 k+ H( U0 o- x  ?# D( Y& J4 Z' ~) U$ z8 C9 i, \8 ^1 g
$ m! ]! W! r7 W9 Y2 j6 e& v
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-9-22 04:11 , Processed in 0.067705 second(s), 22 queries .

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