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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:" D5 Z6 ^9 _. {

" L9 M- a$ w7 Z4 ~, q1 ) . 大于,小于,大于或等于,小于或等于
: [/ O) `! w$ ?2 \+ O* I6 i( s" D- P+ H% L
$gt:大于
4 G& J  o4 o3 Q8 v$lt:小于' S, Z" S% {  e; L7 `& X
$gte:大于或等于
. L$ M- p& \& e% P( \; D& F' |$lte:小于或等于
, k/ A* W4 o% L/ G/ ?& Y  {" Y' W. \- w! {6 h  ^
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value" ?$ r$ |) ~5 K7 o$ @
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    # p0 N) s4 Z( _" y" s" o4 z
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    9 Q9 d5 J2 P% q# W% a5 G
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

/ W' Y2 T5 l$ d. O& U- X" l
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    6 H- C- k: L& ~) @1 M0 H
  2. db.things.find({j : {$gte: 4}});
复制代码

0 m$ S) N0 P3 j2 Q
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
4 g0 Y, |) |9 l
% q+ V% i/ g% j) M# f

  o& q  D6 {5 C
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

  w# U% e# E) m- C
3) in 和 not in ($in $nin)
0 s+ M9 B' e) I& x$ K
5 ^; T. F( c3 Q+ b4 ^1 B语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
, A9 H. f  @) S0 b
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    ! l# S' D  z/ m( s
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
+ Y5 x# e1 f) P

5 q3 T. }& h1 U, w4) 取模运算$mod
' @& @+ w  R. a9 r1 _! [$ S5 d( `) Y; J/ h2 ?& g5 G
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
3 x1 J3 u" s+ x; V- ]; \) a
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
. B- {& b8 A) [8 @  [7 i

9 d' y0 b: v+ C$ D5)  $all. z6 f- K- y+ C' n
! t: N. k5 Q$ p5 n. ?
$all和$in类似,但是他需要匹配条件内所有的值:# F) T  F% Z! @  l" I

4 S1 ~! X' T" A& w; k" a如有一个对象:
( D3 I& u. v1 m
  1. { a: [ 1, 2, 3 ] }
复制代码

9 N8 D' n7 |: k3 s
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

: r7 T8 {- C. N. l# P
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
$ c7 a) u" r, p; W

8 J+ c- G0 B; p* @  A+ _6)  $size
4 U9 Y  Q: F4 M2 v6 m$ s0 V" z  C' J: B1 j
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
0 G6 b" `/ m! }" U% a1 b' x, |
5 J  X* \/ C3 v  Q% E, j! M7 F下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
9 L$ K. H) G1 w9 `5 T
官网上说不能用来匹配一个范围内的元素,如果想找$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.
7 t' j8 y9 {) C( z3 t5 S2 e
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    1 }" X9 P+ D' m1 X
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

* r* h: U. W3 E& w. v$ C
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string" i( s8 o: `- }" c2 s, k
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

9 e5 T7 j6 \3 o3 q' ?- S; v
9)正则表达式
; v. A% U$ N/ J4 \3 [2 o' W- f
% c% X9 A7 R3 X* `8 smongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

' C1 t" w7 m0 ]
10)  查询数据内的值) @3 p% _& P& Z8 e7 R

4 e' O) O+ c7 U; [下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
3 l, i: p4 [9 u- T
11) $elemMatch6 d- \4 j7 o( l
6 P' x! h3 l/ V& m( ^, ?
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    # l; r. I1 {! t# f5 q  X
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    4 e/ N- _! i7 I% j( f; Y8 W
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    4 N3 Q7 Q  E! H# ?- t2 y5 o, C2 T
  4. }
复制代码
: h5 f# D& e" \) \& L* R
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )) l6 z0 E3 P. I, R* X( s6 n' l
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
3 M& y- F4 K, \& M) [
5 o! p! Z! X  m, F, x, Y/ z12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码

' B5 O' \( X- O0 N* d
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
# W! O  D! I$ B* a! _
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
- T. o" x6 q, l
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
, F, `! \' C" S! E) B9 |5 e4 l
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

$ ]6 r! {9 p" a  m
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
6 s) q8 V/ f: S
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );$ I0 u9 V, ~% y% ?  y( \% _: Z
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

8 Y9 z) R0 H' s' w3 g4 j2 e1 q$ d' V
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
0 Z$ V3 F: @( B6 B% t/ r: r3 p) {( [! U' C: Z
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
0 s  Z$ F- s) ^7 d! A. @& k7 I% J0 b
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions) d8 v% y: \" L& Z! e% C  j0 w" v

0 I4 {0 A/ E% ]5 ?. c7 t版本二:
1 j9 L( y/ B0 |. d
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

/ W6 u8 ~4 t5 d6 b# S2 Z& U/ U. O% U
  1. use admin
复制代码

0 }2 U* K$ `! d, y. n  g, G
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
( e* F" r& v: n% {5 X
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

5 x/ ?* m0 u% w: t+ S4 d8 {
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

2 C* N& O) z. ?+ X' x
         5. #删除用户
  1.           db.removeUser('name')
复制代码

  d4 v5 V% ~2 v* j: l* \
         6. #查看所有用户
  1.           show users
复制代码
! `% }( K7 C+ R" T, h4 U
         7. #查看所有数据库
  1.           show dbs
复制代码

" ^" @' C: Y: R4 f8 J4 s
         8. #查看所有的collection
  1.           show collections
复制代码

" V) I- ^" ?0 q, ]( F8 N- A
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
1 P& `- ~' J" b# O) @
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
3 t# O# J- C7 p! w2 F
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

& Z! \9 V4 M& E& l
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
4 b. W& t  O$ v
        13. #查看profiling
  1.           show profile
复制代码

1 Y1 z* W  L, O% H7 @9 z8 k
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
/ k9 ?3 |9 v. M, n7 K
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
3 ~) J0 P+ T2 }7 A8 N- ^% Y' O
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
) T( ?4 n  s7 Q$ [% g/ K
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码

9 M% e$ u- H- Z1 R& l: H2 H
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

  R9 a* \8 F4 P8 V" j# t4 t
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
# j! V3 w( r8 ~+ E! [! r& L
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码
7 ^; y4 m/ c, G6 @+ d
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
- r" y8 ]' O$ y( m2 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()

# r5 E( T/ l6 f! A* S' c
6.  高级查询
条件操作符 - M1 @7 h' h) y& G5 J' D, X
  1. $gt : > 6 d: e$ o5 h0 @
  2. $lt : < % ]; y& e* j4 Y
  3. $gte: >= 4 I9 F5 A! E( a& T7 k
  4. $lte: <=
    9 u% [/ b7 ]' X* r
  5. $ne : !=、<>
      t  I2 x( `% ~0 t
  6. $in : in 6 B4 N/ ^' Z+ V7 \# d6 k
  7. $nin: not in
    & M! B5 Z0 w+ g6 |* U; E
  8. $all: all
    . V9 ^! l8 u! B, }. S' o
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
" _1 M! L8 [& {3 G

; }/ Q  g6 |8 }查询 name <> "bruce" and age >= 18 的数据
( r! N4 I% l  E6 o& R, z/ `
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
3 |) S3 N3 l$ e7 l/ ?, l" }

3 c. E1 W; C( J+ ]; \) S查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
9 g& [  q4 O* \( a" E4 p' F' l
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
8 S# q  t  a% r/ f4 S3 p4 R
% ?' }1 I7 Z; ~' Y
查询 age in (20,22,24,26) 的数据 2 j: v" m5 B$ Z' K  X( V: }
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

3 ^. @( o. H! z* @& A$ x  H" p8 g  a  l
查询 age取模10等于0 的数据 0 Y/ L* x) Z9 r+ H; K% i( L
  1. db.users.find('this.age % 10 == 0');
复制代码

" C! U7 H6 Q# x. }或者
1 q" J7 X5 g5 o  D  l7 z" z
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

5 S2 L2 O5 _# _/ a' ~6 e9 T$ v8 {: m5 l* H2 w# [- Y; s
匹配所有 ' X9 h7 o: k% c! o2 i7 O( m
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
/ @0 S' P3 S$ m
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 8 }2 H6 I3 N8 ^. [  ~  a& y7 z: q
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
$ H' t1 k6 U$ \' t* }
. H* J! c! O( }5 L+ ~查询不匹配name=B*带头的记录
8 t( g1 O' X* N+ g, h6 j
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

( r! O# w) T/ `! e9 y: W4 x查询 age取模10不等于0 的数据
6 a2 W( M- f" |) R
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
$ A* E/ m2 I- H6 ]: d, `& q) q! O

, m) k. i8 u' x9 d  R, A/ X# _# z#返回部分字段 ! B, c( v3 _9 f5 Y: H
选择返回age和_id字段(_id字段总是会被返回)
* E1 R$ C* y7 T2 v4 M0 `3 T5 u
  1. db.users.find({}, {age:1});
    6 |6 U( e$ G2 _1 e  D$ N2 q. T
  2. db.users.find({}, {age:3});
    $ v+ |/ ]- @( @9 q
  3. db.users.find({}, {age:true});
    6 O+ z& b. ~& c7 E
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
5 P8 {" d/ y/ B7 ?% i
0为false, 非0为true ; s: s* x+ C. x: p- l" Y
- b% O; A% O. }
选择返回age、address和_id字段
+ I4 a2 @* C- q5 H6 z" E$ @" h  P
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

! ]# m$ c" }* e: N1 q
  o# S  S& D8 a  ]$ e/ ~: E2 f% j7 d排除返回age、address和_id字段 4 N" {4 n& s! V" C* |% V
  1. db.users.find({}, {age:0, address:false}); * \$ W# E( C* T! r: u$ C
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

: O+ v; r3 F8 \% g* {# c( n* y" c! Y4 p
数组元素个数判断
; V& c+ N+ x7 F( g! \对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
# L2 j. x8 _: e; {$ S4 N; b匹配db.users.find({favorite_number: {$size: 3}}); : W! A, }- b6 x9 h' e. }  B3 i- p5 e9 `
不匹配db.users.find({favorite_number: {$size: 2}});
/ u: T3 G' K8 n9 {. R8 U
1 B3 s% ^' ?. h) z* E$exists判断字段是否存在 ; p2 c9 @! o& m4 n8 V
查询所有存在name字段的记录 7 T) K& h! S: \' i
  1. db.users.find({name: {$exists: true}});
复制代码

9 ~' m+ }' v. r, @; V: C查询所有不存在phone字段的记录 ; n/ Z- K$ u4 x6 R# m
  1. db.users.find({phone: {$exists: false}});
复制代码
1 o. b- c$ U' \& h; d
  u$ T5 v  {0 s
$type判断字段类型 : p" F# \% f6 P4 ]6 r, @
查询所有name字段是字符类型的
; X* M5 _. z; d+ Q/ j
  1. db.users.find({name: {$type: 2}});
      t9 K+ t0 r$ Z- P- Y, Q5 c9 y
复制代码
0 z) `$ l# ~3 w, R% E
查询所有age字段是整型的 # ?% |3 S/ r; R6 \
  1. db.users.find({age: {$type: 16}}); * ]3 S/ h" w, E% b. |
复制代码

( `1 u) h) s, R4 d7 D' E" W! |对于字符字段,可以使用正则表达式 . a  ~8 W) ^. |4 ?3 A) c
查询以字母b或者B带头的所有记录 $ f" Z' s4 g. o  w$ H
  1. db.users.find({name: /^b.*/i});
    4 E( s, x$ e' u" N- o  e) y2 ~
复制代码

$ v# b6 D- b) P$elemMatch(1.3.1及以上版本)
4 s9 \2 E# c2 M为数组的字段中匹配其中某个元素 4 `3 F# K, j" J. U4 {1 p

+ F) c2 ]! t9 `+ K- `Javascript查询和$where查询   c& N, R, ~! C( L9 K
查询 age > 18 的记录,以下查询都一样
5 w. z- n, S" n" f) E( C
  1. db.users.find({age: {$gt: 18}});
    # k: @5 U/ d- b0 g
  2. db.users.find({$where: "this.age > 18"}); $ R. U. I2 H2 e" V* @9 E3 J* p
  3. db.users.find("this.age > 18"); # W( z+ A5 @) V
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
' x9 y. s, c3 M+ o2 X" c
9 ^5 P" r6 r+ `( L
排序sort()
  Z& @! H" R" V' y* m1 ^$ i) J以年龄升序asc * ?3 B3 e1 q& @1 k; h- I+ `; |! B
  1. db.users.find().sort({age: 1});
    / Y1 U% e4 y2 J) i3 G
复制代码

0 Z* {* k# o5 l6 m" r' v以年龄降序desc
: y. C) [, I7 g( w- x- e# b& n3 s
  1. db.users.find().sort({age: -1});
    4 k* e/ i* F' t: `; m# o
复制代码

, P( F" E2 m! i4 f* Z' A限制返回记录数量limit()
* ^  f0 Y9 [4 v返回5条记录
5 v) Y0 x. y  n0 z) X9 n
  1. db.users.find().limit(5);
    / Y( S) |3 b+ j, @  r; q4 v
复制代码
  B7 E9 F' R6 M4 E4 s
返回3条记录并打印信息
: b9 R! ^3 A4 t. h& L+ T
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    ' }' `( T3 R' w, P& \6 n. D5 \
复制代码

: a, C3 K! w  P* x结果 . }+ R+ ~( D- B# ]* @1 K  M& G
  1. my age is 18
    " u* e7 N; A) ]' c
  2. my age is 19 : C, _, {% B. [) a: e# t. h
  3. my age is 20
复制代码
& ~! H6 x$ s( [+ f7 o

" s6 g3 D& r2 C5 M: m( a限制返回记录的开始点skip()
4 j) Z, B3 S, I/ m6 V从第3条记录开始,返回5条记录(limit 3, 5)
4 r' c3 D8 E" l# D2 S  `+ S- i
  1. db.users.find().skip(3).limit(5);
    : z2 M0 t( K1 ~9 x. C/ m
复制代码

% {: E7 F, \2 _查询记录条数count() % U3 h0 }; G# U5 s
db.users.find().count();
1 u( M. J* z- O4 y7 u' wdb.users.find({age:18}).count();
! G- z  v: h8 h! r# ?' Y2 a以下返回的不是5,而是user表中所有的记录数量 : e$ S; y  m* J; x
db.users.find().skip(10).limit(5).count();
1 A- O, P. f5 W. l如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
2 _: q* t/ [' d5 h( S
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

" @6 j6 N1 N! z1 J) z! A2 C
. y! |9 s% c( L. e. f分组group() ( n- f4 L/ [8 H* o1 b0 }% ?7 `
假设test表只有以下一条数据 1 P9 D+ ?3 ]# j
  1. { domain: "www.mongodb.org"
    0 _& ^/ J) G! N. K6 I- @
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    % Y1 Q* I: Z0 q; e* o4 b
  3. , response_time: 0.05
    / P7 }1 L1 o5 k! j6 N3 p1 Z5 \
  4. , http_action: "GET /display/DOCS/Aggregation" ( y# }" G& V4 t6 {$ `! i' `8 \: m6 V
  5. }
复制代码

2 D+ h% q% W, I5 J$ U使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
6 \/ t. ^) h) |8 F$ `! v1 U; h/ T
  1. db.test.group( - O( S0 ^; B$ E/ y2 L% v5 e
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} 1 g9 l) @( H5 Q; `
  3. , key: {http_action: true} ' L$ Y$ Z: P+ }+ L
  4. , initial: {count: 0, total_time:0}
    1 y- e( a! m: Y7 Q
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } * q- H+ m( o) I7 I) s" J7 v) M
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    6 F: U% d4 W4 v& r1 n" W6 F6 I
  7. } );
    $ _5 M  l, l! S% J3 W
  8.   P* I7 v9 G5 V
  9. [ " ?9 s, T  g2 r- H
  10. {
    2 z6 T  k; Y/ g$ S
  11. "http_action" : "GET /display/DOCS/Aggregation", 3 n# z6 X7 n/ Y$ E' L
  12. "count" : 1, 2 L8 |* S6 F5 o# ^
  13. "total_time" : 0.05,
    ! J1 w4 u5 X! x$ ~& Q2 d
  14. "avg_time" : 0.05
    0 v$ a- Z+ c# h8 Z4 k3 H
  15. }
    , }$ l" F6 I! k8 O% ]( o
  16. ]
复制代码

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

. d3 O5 W, }( P8 j. `) T
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct' n, {. N; X0 Z  O
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
4 z' s( i0 ~$ E1 m, G) ], _
8 A& p& o7 T( x
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

. f( L# q" o5 Y2 o; i# I; l" b) ], L. J$ a* m3 l3 c: s
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

* }! q% F3 E0 G$ ^, ^# M* o$ o, v) u( c- i0 h2 w
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
7 h/ R1 X* f! J' c9 @# {
0 u4 W5 H; F) M, Q+ _# ?+ d) L8 a
输出如:
  1.         - \+ a1 ^8 J3 v1 _8 }5 g7 ~
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

5 U! @( y$ P# F5 L1 n2 ]0 r* p2 f) G7 _) x+ U5 C4 d

& y% i, _' U; ^0 c+ P1 z! M" O5 q" _  [* K
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"
    / U, T! J; `% \; E5 y& ?; C, ]
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    ' y! d: O0 [0 l0 n: Q2 V1 s
  3.        xmlns:context="http://www.springframework.org/schema/context"# D  t& M% O+ m1 [
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo". ~: y' {, |0 M5 g) I+ @# ?9 _1 N1 K
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    7 H5 I' R7 F% h. ]4 ?
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    0 D1 H1 P2 x; c  X' h) k
  7.           http://www.springframework.org/schema/context. w* t4 q3 U; m) x7 N$ N
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    + f& b/ v0 E" s  g. i
  9.           http://www.springframework.org/schema/data/mongo
    5 ?8 O  J% R' \
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">& T& h9 M' F( U2 o8 O, |( @2 j1 A
  11. + ^8 }2 n3 p5 @+ B+ ?
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    : N) i% C  C5 z6 x
  13. ' ?* _9 O9 i' U# o
  14.     <!-- Default bean name is 'mongo' -->
    / m' c+ n4 l/ V+ V/ d/ V
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    ' Z9 e' F2 r" Q2 p3 o3 o
  16. 9 g0 f/ q3 l# {2 D& a7 ^/ `
  17.     <mongo:db-factory id="mongoDbFactory"
    7 R0 ~0 l0 z$ V6 x
  18.                   mongo-ref="mongo"
    8 i1 n; Q& j6 P1 A
  19.                   dbname="mongotest" />" t! B9 ]5 d' [) L7 c% N1 D+ Z- t

  20. , c0 Z  l7 X7 d: w0 j
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    " q- ?0 u( h0 `
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>" y$ [, x/ e( J) `
  23.     </bean>, p* Q8 F) r8 z8 M+ B6 W% N
  24. </beans>
复制代码
: w' d5 _" K. F7 T: ]! S
1 l" h3 y8 ]0 O0 Y# \- G
maxmin的测试
  1. @Test
    * |9 H5 s* e& c
  2.     public void testMaxAndMinAge() throws Exception {+ z2 V( A( M  O% R
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);9 E. p5 S: x0 K5 y
  4.         Person result = mongoTemplate.findOne(q, Person.class);: O: V- L' O: [, T
  5.         log.info(result);
    1 I- F( g& |4 W) c+ i
  6. + K  s  X' G) w1 y6 a
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);4 j0 x7 d2 A/ ]5 O
  8.         result = mongoTemplate.findOne(q, Person.class);
    0 K8 p1 b* P5 s: C+ ^
  9.         log.info(result);9 t, p8 x4 S/ N8 }
  10.     }
复制代码
" v" a4 O) i( V! s+ @0 f' G
' d7 X7 j6 d4 q7 ?( ^
distinct的测试:
  1. @Test
    0 {; U% f+ s( Q) N
  2.     public void testDistinct() throws Exception {
    0 [  J& g+ N9 h4 x# l2 F8 e
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    / @( S) {8 k* k* G$ R
  4.         for (Object o : result) {/ t2 G$ k* O& J7 z3 k5 s
  5.             log.info(o);* _( V1 o/ v! Z8 s' u  |9 j+ s
  6.         }
    6 N" z# ?; \7 L& ^  ?
  7. * I8 w& i/ u: v& W* b
  8.         log.info("==================================================================");. ^; Y, J4 U7 h8 z0 ?- D1 o" {! Y
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));5 m6 Q% i% E, }3 s* e
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    : M7 D; u4 ^9 A. [" d8 }
  11.         for (Object o : result) {
    3 ~3 H- K: t5 X! W, }) k3 g. V# w
  12.             log.info(o);! k  a( W' ~( d$ ^5 x/ m
  13.         }9 V+ M2 G# e1 e
  14. 1 p: }' m; ^: B2 J2 V, F
  15.         log.info("==================================================================");( N9 c- j0 y1 S+ E
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    % N# _. y* N2 N; t# {; s
  17.         for (Object o : result) {9 [" e5 C+ r0 P# X
  18.             log.info(o);
    ( Q& W4 C$ @; R4 F6 j" i) A
  19.         }
    1 e* v8 s' c- h7 Q: A4 {
  20.     }
复制代码
- L2 C$ _" L& m: S# f7 j

1 r. h8 E7 |/ C- k
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567* `7 @6 l  W) H, ]% j' i
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    ! v, E8 E. c$ U/ q2 d
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789* Z7 O1 p& V* f8 h% S/ x8 s5 N
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 9876541 a5 k  R% v8 a9 K
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    ) R( S9 @7 y' K1 t) V% S3 v8 C
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo7 ^( t7 v; V1 D/ ~+ A
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 1234565 e# _( x1 \& T- F
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    6 c: E) n, n1 C+ `. w5 e+ Q5 N& M. L
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    $ S7 \  \9 r6 m) b  p& ~/ D8 C
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    * L) M1 z2 H( U1 R8 f' v6 O
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    / p. l" \  }" I. c" G6 U; [
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    ' }+ U0 H2 J- U9 J! [$ f& W
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================/ i; q! M: q9 E' t, q
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    8 }3 O7 ?% r- q; J
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    & n) n" Z# D4 v: s* {
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    , V5 I# f5 j9 h) L2 I
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www& E3 R8 L' z, @: L6 R
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx. `; k6 p: Y0 @! r* q. w
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy' k5 w$ \) A) \4 }& C' c# Z
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    ) h: f/ x' \( l
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    0 S  G# ?7 s+ p4 x# a
  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
复制代码
9 o* }: M4 t! p) F% H
6 c& c6 N% t/ T9 |
这里我要特别说明一下, 当使用了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等信息。

* N4 c! B: t: {0 n4 Q* n9 {  x. D9 v, p/ K5 N
: A, D( n' T; n( c1 o2 n: f
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-4-30 19:57 , Processed in 0.070682 second(s), 24 queries .

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