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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:+ T/ F$ W7 L3 |

7 q. g' e7 S" w1 ) . 大于,小于,大于或等于,小于或等于/ O, Z  N/ q* x( P# F$ T
! G* E& O, j7 K3 I! W1 Y3 }
$gt:大于
! C: Q; o9 q' W$lt:小于- G) A6 o* i% Z- [0 A$ n4 g
$gte:大于或等于% `- K. J8 ~! w4 o, k& G
$lte:小于或等于6 }3 n: t: @. e( ~( J% A

& h& x) h1 i# C4 E7 d例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value. K9 R0 l. Q! k
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value" g( T3 j: m7 ?9 x% F
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value8 {& E9 T3 Q* L1 i
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
6 f- ~1 V: Z/ I, {, F5 d. u
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    . Z# x+ @+ |7 l
  2. db.things.find({j : {$gte: 4}});
复制代码
  u( Z4 j3 B3 z
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

, ^) c* }2 T; e; B0 ^: |# P8 c. j$ w4 @
1 @. P: k. _3 s6 d) h2 h% H- ^
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

, E9 I- s$ ~# j  R  d$ [7 h( ?
3) in 和 not in ($in $nin), I6 \! {& L3 _

# i( b  W9 h, n% ]: N/ q$ k语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

+ v; V$ z. Y0 Y' b7 E* e& f
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
      ^% c+ v& }6 {
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

% k8 l, {1 y4 T+ E/ X, u7 U3 Y# a

3 d+ ~! I) K0 e4 |. ^5 e4) 取模运算$mod
6 N3 x# P6 ]8 X2 E9 o0 n+ v* s: F& l) I# k0 V  v
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
! t! ]( ]8 h+ `# x# }# |
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

1 `2 h2 b8 _  X2 U3 _5 l

5 _+ k! h" ~0 }6 T1 L5)  $all# H% J- S" }: ]2 o

  E0 A$ O/ f$ ^  O$all和$in类似,但是他需要匹配条件内所有的值:
- B- G1 D& B6 n4 c  j/ ]! |7 d
5 e/ v0 H/ ~2 {如有一个对象:$ \8 s' Z0 A( k1 ]; h, I1 o
  1. { a: [ 1, 2, 3 ] }
复制代码
" H, s- ^# a+ G9 s1 o
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

$ k& X& r" n6 b4 x
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

( e  H9 f! `% ]$ C, `

2 `1 J1 j) |+ |  j6)  $size: L# e# }( D3 j" E9 J

8 Q. A6 Z6 }% I! @/ b$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
# @; E& l: f9 v( H  d2 A( [9 p6 |) ~
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

8 k' S8 Y, V- r- Z: G0 J% P! `
官网上说不能用来匹配一个范围内的元素,如果想找$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 y7 S% r  @& K% a& b* {% e
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    - s3 s1 {) i' Q6 E( J
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
4 g5 l/ Z% s0 r6 H; a+ Q; b8 D; X
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string1 Q4 ]) ]  w3 g; k  B
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

5 C5 e1 ^  h/ \1 E4 b* Z; B# P. {2 Z
9)正则表达式6 V% G0 `, ^2 R
4 r. H3 L7 D  ]- h
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

& u8 r3 m+ c; p0 w- X  j
10)  查询数据内的值- {0 w! n9 J9 C' F9 h
0 h% w3 x: k  C! q1 e
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

& J6 J; s7 k+ d% H' H6 j
11) $elemMatch
7 _( Y. V6 Z6 g9 O8 Z6 v
. o7 `2 ]! R7 [# X如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) % ?3 P1 f9 S! h% C) J% Z
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    , S1 n/ a; a2 j6 K/ D! _
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    7 S. o2 \2 I: ~5 V
  4. }
复制代码
  @  A4 k, ~& |! c* Q
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )- @: B1 r9 g- O1 ~
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } ! F: ^1 s7 I/ n$ f3 s  ?) B7 v9 @
  |$ o6 P0 I3 t* X& w' o! f, A/ @
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
3 Y$ w" P* \9 P+ n
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

2 v# ]% [1 }: m: O( w
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
( ~4 A$ ?7 ^/ T% @6 ~/ M( P
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

/ M7 x3 _2 F: s% _: l
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
# H( T5 U+ `# c+ c! k
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
4 @7 a6 g' Y8 L5 ]
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );
    ; P8 J7 P- j) a$ _$ |
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

( p# x6 r; @  Q. X3 \  c' `( S8 u
mongodb还有很多函数可以用,如排序,统计等,请参考原文。+ S& R, m3 J& Z3 `3 h  {# s! r

" e( g" D! |2 P) @6 `* F' ?mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
* |4 R2 W  k* V
6 B% ^+ U. ~9 a5 k0 j# U3 {, J7 chttp://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
* u7 g& e. l% t) _9 u4 g& `7 g5 Q& M2 R2 o  _, f7 t* N( R0 a
版本二:4 B% o3 T  W  W6 L' x
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

6 Z9 m! O% j! o, @9 P
  1. use admin
复制代码
' a1 W* X5 J3 b+ H: L1 L/ \
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
4 j" G! O' h/ L+ N. r* k
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
$ U" L3 j0 @( ?; T4 z
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

5 f/ _: E8 \( V+ v
         5. #删除用户
  1.           db.removeUser('name')
复制代码
/ V8 ]$ [2 l# y
         6. #查看所有用户
  1.           show users
复制代码
* ^" f1 w, @# o- J& P" _
         7. #查看所有数据库
  1.           show dbs
复制代码
1 y+ D% \  {/ k- B$ U
         8. #查看所有的collection
  1.           show collections
复制代码
* G) P4 x3 X$ t
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
1 ~+ w2 k) u, v+ v5 j( a7 r4 R. n
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

- z9 E) l( b% h# D: ^! b
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
: o$ E5 }' G6 T
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

' X3 e+ W9 D& T% [6 z  `. @! s9 I
        13. #查看profiling
  1.           show profile
复制代码

$ |9 ]1 r. j$ N# D$ ]8 i
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
' n( z" F! v* R( ?0 G
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
6 y, X* g+ j8 ~5 n% m
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
, S/ V: n- f, \: l9 H
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
0 |! c. S& K( }
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

; n/ X( K& s+ o  [* j: H
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
7 A8 l. L2 V) i1 L
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

. l- b$ E$ m( f$ z, l* }- b
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

5 X! g; B$ L: C& F8 u( C5 Y" k
   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()
* C. y& l7 h; G0 K0 y8 F- V
6.  高级查询
条件操作符
  M; l: ]# i* p- Q+ [
  1. $gt : >
    : \8 r2 @( f6 t% {
  2. $lt : < ( m; m8 C& `: c. J4 k* a# i5 ]0 j! H- Q
  3. $gte: >=
    + x- E% N/ e2 B% r! k- m. I5 N
  4. $lte: <=
      `) v; d3 c0 Z; W5 L7 k9 d5 z* J
  5. $ne : !=、<>
    3 Q, Q) r' C- A: A+ [
  6. $in : in 5 F9 e! Y6 O; \/ y; \: p
  7. $nin: not in 6 V, s9 g. \4 A: Z% P9 R
  8. $all: all
    / G' w" i. b7 T8 b
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
5 G1 Z. c; G7 z/ o7 D

9 Z1 n3 B$ s0 E0 j查询 name <> "bruce" and age >= 18 的数据 . M5 e% C7 `3 C# b; ^& e7 e6 y
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

% n3 S7 h" U$ Z8 |# x8 X$ X! [
' B* V- o& Z6 P2 @查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
( ^+ ~& `7 T) ]% |- A) P$ j
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

! A& }# l% g4 \0 F0 U8 w  r' q2 E3 X* U; P
查询 age in (20,22,24,26) 的数据
4 W2 Y/ c% b- E  K
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码
( V0 ]" M& \2 c2 G( f/ V

$ o8 O* C4 O& v. K查询 age取模10等于0 的数据
$ Y9 w" G5 q* v6 H" L1 b
  1. db.users.find('this.age % 10 == 0');
复制代码

: W3 d+ E9 c2 z' [8 d" w. u4 N或者 : E. E' E: P  f9 L
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
) a. T' v! Q1 ~. B% f: r# ~7 q

1 z: m5 N$ l9 E- G( u' N匹配所有
3 ]: s2 `6 |# A5 }( G
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码

$ {5 f, r6 Z# q9 G4 b7 D可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 8 Y! I5 }# W/ \1 ]6 w
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
0 n) q, h' Q* O& r+ m) q* R/ k2 U2 y+ x* c; I# d/ b1 E# m1 V3 ^
查询不匹配name=B*带头的记录
. R4 r1 j" P" S: Q
  1. db.users.find({name: {$not: /^B.*/}});
复制代码
# i* n2 R- v8 K0 }! a& W# O! h
查询 age取模10不等于0 的数据 1 U* F+ q. l- A) f) z* Y" i1 h" T
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
7 q( {- u  `9 {9 T# v

% j. v2 n6 b( @( X#返回部分字段
( l% N. B( E$ @% O% J" u选择返回age和_id字段(_id字段总是会被返回) $ h+ N1 B1 `- f$ J2 @
  1. db.users.find({}, {age:1}); $ R0 p; g8 h( L, }6 B
  2. db.users.find({}, {age:3}); + F4 {+ X  |$ ]0 v% w- i
  3. db.users.find({}, {age:true});
    # b  F( {) _$ I$ q6 E0 `4 Q' U
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
! h, \0 L4 P4 C3 S
0为false, 非0为true
: y6 D' J; |* }9 ^5 f* O; L2 w
选择返回age、address和_id字段
6 r' P' @* ?2 T$ r1 K
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

6 {0 J8 c' z6 {9 Y% B/ N3 V; t' \2 F, m' X+ T) \
排除返回age、address和_id字段 ; v8 a) I  L$ \% b, n* `) t+ r- |/ g
  1. db.users.find({}, {age:0, address:false}); 8 G3 ~9 L- A* P9 ~
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

( t; h3 E# v9 ^. a* {  }+ D" j1 k$ x9 g0 b0 q" x2 ^, f. M/ H
数组元素个数判断 5 T- s$ T- O% }
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 # {$ F7 B$ c& q' O# O
匹配db.users.find({favorite_number: {$size: 3}});
2 H" F# j' h) F1 a不匹配db.users.find({favorite_number: {$size: 2}});
& x3 [, L. v1 [4 s, w
) B& g5 u. y! F7 P0 _$exists判断字段是否存在
3 N* w$ d, O& ?$ K) y% H3 z查询所有存在name字段的记录 . }0 ^% Q6 _! _; t
  1. db.users.find({name: {$exists: true}});
复制代码

1 F, [9 g0 Y4 f查询所有不存在phone字段的记录
; S. n4 X' l0 H9 S
  1. db.users.find({phone: {$exists: false}});
复制代码

' }3 [& n1 u6 ?2 O
! V, y- I! {$ X2 F$type判断字段类型
7 h6 [4 g- x4 Y查询所有name字段是字符类型的
1 t6 j% x( ^% k$ K* Y1 b
  1. db.users.find({name: {$type: 2}}); ! [, D4 H, g! y! A5 `6 a
复制代码
+ o8 Z8 t5 J7 i& F, L' T/ V
查询所有age字段是整型的 * {0 J" f( [- O: H7 P1 t4 ^
  1. db.users.find({age: {$type: 16}}); ' ]3 b2 c5 Q& u; E0 _
复制代码

5 K+ u" P% _+ T5 w& F0 T/ C! l2 \5 g对于字符字段,可以使用正则表达式 6 W/ k( w- D5 F' `
查询以字母b或者B带头的所有记录 # }& H8 r5 C% A% A
  1. db.users.find({name: /^b.*/i});
    2 M! Z& q3 N7 H1 E
复制代码

2 C3 N+ P/ R# c$ L, o$elemMatch(1.3.1及以上版本) ! R" Q, [- z7 U5 U5 H+ r6 r
为数组的字段中匹配其中某个元素
& J# N2 i4 b$ b: Q( o/ o& s* r  V
Javascript查询和$where查询 4 e( v/ e9 Y% L/ O( \2 [
查询 age > 18 的记录,以下查询都一样 , D5 E1 S& G5 x
  1. db.users.find({age: {$gt: 18}});
    0 K- Y2 [1 P7 Q+ p
  2. db.users.find({$where: "this.age > 18"}); : n# Z8 G% B8 t5 j$ g
  3. db.users.find("this.age > 18"); ! w1 c1 \5 N5 s, f
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
: s5 j7 n* z8 m5 G/ i
6 x, H6 a$ P2 n: k& h
排序sort() 7 x) S: @- w. w7 |4 X
以年龄升序asc 8 Q: E/ p% l* f  \3 C- H
  1. db.users.find().sort({age: 1}); + ]7 c6 h+ R+ V5 x7 Z, s9 V
复制代码

$ M  M" W1 @- K' F  b/ r0 t以年龄降序desc 8 X+ p+ }8 e% {. K* l0 `( _+ I. `* Z
  1. db.users.find().sort({age: -1}); ' G3 h& ]- R) f' [7 [' |
复制代码

* y. S4 `$ b1 z2 v" R1 G限制返回记录数量limit()
% n: i- N8 g7 t% T+ e( a返回5条记录 : L; v6 M4 u/ \/ ]/ e& S) |5 c8 s
  1. db.users.find().limit(5);
    # i$ K9 s' A' G" }
复制代码
5 a' e/ z6 Z9 {$ f, d7 C) l/ t5 O, n6 h+ W
返回3条记录并打印信息 0 u0 X5 z1 i7 A7 e
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    2 d% X- D0 s6 d# k0 U/ Q
复制代码

! q" t! O  g" Q8 `7 r; b) m结果
( i+ l) g6 g" `9 D, W
  1. my age is 18 3 P% O( b4 l( s
  2. my age is 19
      L1 d( @. \3 S  T  Y4 a
  3. my age is 20
复制代码

: `; t  v1 H/ P- @9 Z  @) ?" l& f! z" i0 ^) ^4 f
限制返回记录的开始点skip() - [2 X3 P3 F; X7 ]: O: E
从第3条记录开始,返回5条记录(limit 3, 5)
  Z. D0 p$ B& I. ~& m+ l3 u
  1. db.users.find().skip(3).limit(5);
    0 r+ j3 l% F# H4 R" W( H
复制代码

4 j0 |0 l/ G9 {5 x; b查询记录条数count() , F, h! O4 r( F, V( d$ P1 A6 B
db.users.find().count();
( ]4 |) @% h" ~8 n; _; g. vdb.users.find({age:18}).count(); 0 w2 o" F0 {. K. K( @' w, I7 q
以下返回的不是5,而是user表中所有的记录数量
8 m+ `& g. R& v- wdb.users.find().skip(10).limit(5).count(); 9 v- V5 v# t; X. z  i/ Z! k& L7 l
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
  h& ?2 L' h+ ~3 ?- S% j
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

( r7 H7 W7 M5 ~8 N  {$ Y+ u' n. U+ r# l. X8 R* V% ?
分组group() # u& f/ {  u$ f7 ~3 s. F4 E' y
假设test表只有以下一条数据 1 q, K3 b- X- \. |. ]7 I
  1. { domain: "www.mongodb.org" ( h) G9 U, P( c# x8 S8 l/ F5 E
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    . A' K2 r/ V) E6 R  p) ^1 b$ d
  3. , response_time: 0.05 5 t+ v( }' v6 D9 \
  4. , http_action: "GET /display/DOCS/Aggregation" 8 \& ]& o" K: d8 K* H$ r  i: R
  5. }
复制代码

; O0 S5 h6 p( I+ P8 K3 ]使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
: y7 k; H3 [; H" _2 p# s
  1. db.test.group( . |* @" g: m' V0 j( @! k
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
      t; m6 d* l: m3 ~  s
  3. , key: {http_action: true} - X8 ~" X2 @2 e' P% n1 |; ~
  4. , initial: {count: 0, total_time:0}
    , y6 _  i9 }: Y9 ]! h
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 2 {/ X- [* @$ m2 y& g
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    . ^) D. y, v  O' e
  7. } ); 4 d8 q2 s2 [  z* I4 ^/ D* Z

  8. 3 X: z! O0 q$ u, [& x
  9. [
    . @' N& X4 j4 a8 |( K  ^5 J$ j% c% b
  10. { ! I! R# z% k! ^4 ]7 j: H2 o
  11. "http_action" : "GET /display/DOCS/Aggregation", , x6 V2 d- k  o, P0 n
  12. "count" : 1, * [, d! B% v( b, Y! C! |  b
  13. "total_time" : 0.05,
    ( c' _! @+ Q; K  f& I$ ?
  14. "avg_time" : 0.05 * A: \* n9 [' _' J0 |7 z- s5 j
  15. } 8 w8 ~) k6 k* }8 C% _4 X' q: x  f
  16. ]
复制代码
5 m9 d4 V4 I9 f

4 j# Q" C9 g! B2 e9 Q8 ^
7 I" r4 G% S5 ?& ?3 e1 T' WMongoDB 高级聚合查询
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
    6 W5 @" y; i4 {! @: G) G
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

5 I4 k6 ?' Q* H$ o  m4 {% t1 ^$ ?  K/ h. x% W0 s1 k8 k
% d- \; S5 u8 D' `. ^) {4 ?
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct0 B5 _' R; W  j3 D7 L" J# ]
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码

5 P1 L* U5 b) c1 \7 ^6 T' U' s# P' x
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
' g) Y$ `8 e7 }5 Y

2 `( I& C9 `$ g0 s2 A" |
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

& N9 {) m, ]+ j* g4 F# {3 q( t3 [0 X/ ~* b
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
8 Z( L+ K% M2 E6 S1 X9 r
7 }, ?/ }6 s1 V% v- h4 D; U
输出如:
  1.         
    ( ~" B- x. T1 L% h: k* P3 ?
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
( l% \/ d7 T3 g( {
. C: F. R5 I+ ?" ~
) Q9 F2 B- K- N0 f* O+ I
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"
    5 v5 X+ b8 M+ C$ i& f9 `7 Z. D
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance": a6 L7 s- V' u6 }; e$ _" |, u
  3.        xmlns:context="http://www.springframework.org/schema/context") ?; S* o; E  p% P
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"$ O$ i. R9 y* R6 @4 E- |0 U/ x$ z
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    % I; K! l; @# I
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd, o* ?# b" [/ t3 n7 S: x7 p
  7.           http://www.springframework.org/schema/context  c) v; I! _0 r' o% W" k
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    " X# U# V( [# p, [0 J2 {8 V
  9.           http://www.springframework.org/schema/data/mongo
    ' o( d* e, D: a* N+ _
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    ! l  Z6 K6 U" Z9 j+ q
  11. 3 u4 Y0 \2 ?. b# o. d
  12.     <context:property-placeholder location="classpath:mongo.properties" />2 f6 O' f1 `+ m; }
  13. ) m# Y) U- ^5 W; H# l" H5 W
  14.     <!-- Default bean name is 'mongo' -->/ `8 d6 V6 f  a+ u  B: O9 e6 e
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    . c/ g$ `( U' P- H* S
  16. ( f' p! y( [. y# {1 @
  17.     <mongo:db-factory id="mongoDbFactory"
    : \% X# L( u7 p" G# U) W+ |
  18.                   mongo-ref="mongo"
    $ g" ~+ z) X# x
  19.                   dbname="mongotest" />
    : P( e: y. A6 c( S  l" S

  20. 5 Q0 J' p# J+ z. d
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    $ ]+ e- B+ v* I- h9 j
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>5 w0 K& h  |# Y7 f" o% f# }# _/ H" q
  23.     </bean>9 t7 b1 R; u. B
  24. </beans>
复制代码

/ k. K0 ]4 k$ C" ^

+ u; @' }% j7 H  w/ o
maxmin的测试
  1. @Test
    8 J% y0 b/ i5 R; U8 s! e
  2.     public void testMaxAndMinAge() throws Exception {
      Q& P! \% b( _, p9 z; A- j( r
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    8 m; m" h2 i; `. d
  4.         Person result = mongoTemplate.findOne(q, Person.class);- N: p; P; x. d+ A1 V
  5.         log.info(result);9 `+ Z: g  a2 M6 q; I3 M9 a$ @! A
  6. * ]1 P- ^* a( c( I6 l& c( o
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);6 K1 F9 `; k2 e. n0 `5 K
  8.         result = mongoTemplate.findOne(q, Person.class);0 e; b, L1 ~3 @! Z6 a
  9.         log.info(result);9 b2 @# @% Q, o7 i! _3 Q+ F5 {! q
  10.     }
复制代码
& r! V* I' f! R! h
' _. {1 R( V; ]5 I  V' ]
distinct的测试:
  1. @Test1 }( p2 `8 y  d
  2.     public void testDistinct() throws Exception {
    0 z% D8 t+ O* ^- b; }
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");: E0 r2 C! V+ q/ g* T
  4.         for (Object o : result) {
    ; i% R0 ]8 @' s" z; p' M" }
  5.             log.info(o);/ }5 d& ~- J9 `  F0 V7 A" M
  6.         }
      M9 D( F& t7 q* H. W) X+ ]
  7. + F+ N; _. {5 B
  8.         log.info("==================================================================");/ I/ b. N* A- ^
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));+ N; k! l% s0 w% z1 C% F$ Y+ Z1 |
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());4 i/ |) T1 ]% N5 M3 L, ^+ J
  11.         for (Object o : result) {# ]' Q: w$ _6 `5 N: X
  12.             log.info(o);1 K3 @" V6 E( A* E, v) q
  13.         }
    3 ~# h3 Q8 O; m+ ^
  14. . q; B3 h- [, j: v) t: ~* `+ }
  15.         log.info("==================================================================");8 H# O6 G- }1 P' l) N! U
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    7 I; ^: N( f. i: D* P
  17.         for (Object o : result) {
    / R: x8 C. N6 ^2 Y$ s! V" O
  18.             log.info(o);$ g% W& R6 c  b# X8 t
  19.         }" i; v9 h4 b3 a8 L! k1 Q
  20.     }
复制代码

: @4 ?, ]7 z7 T8 W6 u3 n, Y- J$ V/ L  D
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    9 w+ b# _' v; [
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 3456788 }7 A' w/ p9 Y; u1 K1 k
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 4567892 Q5 u* e3 H4 ]& r
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654& v6 z# t# x7 _9 v
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni% o; `- k# u; @* k# y7 i" q
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    " C3 r* Z( }; ^2 n' v
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456  P0 O( P5 X3 \: W$ V8 v
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================# v5 |$ h5 _. K+ b% ~
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    9 n5 e* H) |! Q. s" [5 g1 K4 L
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678; B& _, W5 i) u+ m6 h
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    + B# j4 N8 @3 g' Z: |7 |
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876540 M$ e/ {2 e- g7 L; L. f
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================, Y# m" Q; N/ K! W: f+ [: z" |
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa6 m; \, ]- G( b' t0 t  f$ R
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    ) h+ q* ~2 \* Z. K
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc* e# P. h9 ]/ ^; p/ c8 d7 D
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    7 g' b) j2 w1 c6 \) i, G! \
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx1 W' g2 U# g5 V( X0 M! g' Q
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    1 X! P; P& r- N
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz5 ~! }! ^- q. e5 \+ T1 M
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    - v/ B+ W1 P0 z: i; 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
复制代码
' W4 n% ]" `- `# H. _# s

- X$ @8 L7 {5 \! f! \
这里我要特别说明一下, 当使用了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等信息。

6 f: e9 C7 w6 y9 h+ U  T9 {& N, y, [& ]& t9 u( ^/ Z! C
8 V) K9 p2 M7 O- W
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-3-16 18:09 , Processed in 0.076742 second(s), 22 queries .

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