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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:/ x% u3 W! X5 z

( n% p( M  w6 U+ g& R% Z, b7 a1 ) . 大于,小于,大于或等于,小于或等于* ]5 m: C4 j& o3 w

" w. ~& q2 j( ^6 ~0 H$gt:大于4 A+ T6 W% [) W7 i, i& j1 H) H
$lt:小于
7 w% i' b7 w& N! X1 K: e# V$gte:大于或等于
! q. d, N  S8 }: n$lte:小于或等于. }: A4 A8 \/ H% V8 F- C  ^5 B

/ n: W7 [5 T9 \/ z; A% k例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value
    5 B2 P7 D! q: o& D2 L* X. }. x* Z
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    * q/ ]2 S# j* x! Q" W' [
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value& E9 |! }6 L: H9 W* K+ p  D0 G; O
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
; |/ d* T. w3 D1 d
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    * T6 r  _" c. r5 t% h
  2. db.things.find({j : {$gte: 4}});
复制代码
7 S* M  j) U: l
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

1 `: f% A4 K8 f. p% o3 F) Y: \' E% A, o
0 j0 C1 c" V3 e; a3 y- _
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

, h! t) R$ l4 g6 Y* ^
3) in 和 not in ($in $nin)) T1 u1 u+ p# X+ z+ g# h/ C

  g: g/ P: m& t7 C" q语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
" z. U7 X) Q1 G/ X6 m
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    # b; a' o0 D4 U9 @. q  _$ M
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

; G) A8 R+ V+ J( l

0 K9 ?% L( F  ?9 D5 \! u$ W6 {4) 取模运算$mod+ C+ u+ j; }) [  D2 l3 I9 t: S
3 B* H8 K0 w  ^2 {" b
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

) o3 C1 M! u/ S+ y7 n) f
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

2 Q. T! a% z, A8 J
" S4 Q! S* A: @% D1 a
5)  $all* _1 y" g8 X' C0 y2 w$ \' f
3 J( `2 u9 L+ z8 `* o* m
$all和$in类似,但是他需要匹配条件内所有的值:+ x; y( `6 S- M6 J

, g0 I% T+ c3 P; l$ W" e5 G如有一个对象:& U1 ?! L, R1 u
  1. { a: [ 1, 2, 3 ] }
复制代码

$ T! f" }$ ]0 Z* _! q& [1 [* Q
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

+ P& _5 y$ G# L! G" k0 Z: I! w, P
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
5 h1 v* U0 a* f, Q6 K; O
+ \" z& T9 G$ ^
6)  $size% U* R7 H) D/ C8 j. q" _, R

# Q7 r4 h) ^4 Q$ u$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:  W/ f+ S3 J. z. D2 w/ b. {. I: j! [
7 P0 Z( E# B) E  R) `
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

- V( |4 Q0 {3 ?2 K3 O
官网上说不能用来匹配一个范围内的元素,如果想找$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.

5 m9 u' `& f8 k/ r4 ?( t, m% Z/ O
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回0 ^0 S, \  |( g) T- s# g
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
: `4 o  V  z: P2 z
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string! I7 h. ]; c0 D% L+ z& }
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
- m: p8 X& x2 X& W# t, e4 y
9)正则表达式% Z- Q& B  V, D* U. P  R1 y7 J

  Q0 i& Z/ {# j& k9 I7 z/ }1 emongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
8 C8 t4 |4 y; H
10)  查询数据内的值6 l) {, x1 s, V: j2 D2 {2 }  {- N: h
, X+ T. ]0 d, o8 H% q& y  }. {
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
8 G4 B, i! s- J2 k2 b+ ^7 r
11) $elemMatch3 [' j6 U. t) W9 Z7 |
4 j0 \) j* V/ }5 t+ [
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    0 |1 d) P# Q; {7 s; r
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  ! e/ S/ p4 N1 \' {6 n
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]# M  `, H2 T1 t( j! ?3 r& o
  4. }
复制代码
- c4 v+ P* Z9 V# }
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
; E' c# U/ n3 w# g, P, A
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
  Q$ `6 A  Y* c& w& `
% w+ M; H8 p! |, H  `- t12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码

6 j$ @* ~# F1 l/ Y6 m
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

, E& C& L4 d. ^0 h  o
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

+ ?) d" G6 n# S# ?; c% g3 ]+ G5 M
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

; A; g" w. K; I( A8 F7 G* C! s$ g
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
  I$ _4 k5 i0 @1 H# i
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
& O/ H+ c" ]* g* |+ f8 i
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );( [! Z8 q8 _7 z6 D3 }
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
) l) d) C; p3 @$ o
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
. a2 \# @7 D4 j, H- m0 ]' I' n
# F; g- \6 G! h; l8 z! T/ q9 [mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
' u' F2 F5 f! s' m
0 r# P! g$ [+ M0 qhttp://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions& P3 }9 |$ h4 n! w% u
1 W; x# r! `* W2 X* ]/ c4 M; G
版本二:" }% W: c+ L8 o/ [
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

  Y& b/ X' ]* M* l" a
  1. use admin
复制代码
& g, q3 U( i$ @3 |
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码

" a; v9 T! s9 r9 K  [
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
9 J8 |5 J3 A1 G5 f
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
4 J; S) L8 v* ~; F. X
         5. #删除用户
  1.           db.removeUser('name')
复制代码

* L/ a! e3 z8 G) D
         6. #查看所有用户
  1.           show users
复制代码
- C: @9 |( k* \3 I' R0 q
         7. #查看所有数据库
  1.           show dbs
复制代码

* A/ _9 o4 k; o) t, o  ?! H
         8. #查看所有的collection
  1.           show collections
复制代码
0 M0 m; M3 o& l4 r) [) c4 x. ]0 s
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
. c/ B0 B1 Q% y8 c* _
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
! r% t( B, J/ y+ ^. H  B
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
3 [+ n" i+ B+ o- b( i2 L
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
& g+ r, e0 l2 n, f
        13. #查看profiling
  1.           show profile
复制代码
' U, u( r7 Y1 p( q' l
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

% w/ W3 c3 z4 z* @& t# h- R2 Y1 F! e
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
7 G" G2 A" q" T$ \+ X& O
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

* o7 I4 h/ r/ g, T
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
4 o% d1 C/ k5 S0 m& Y$ d1 h! }
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
7 I& Z, ?, x5 k) J
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
) K3 \5 G/ [+ v- Y+ ~
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

) n% w+ H- y6 G, V8 |0 W& [) P
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

' ]" B" ^. N2 E9 q. V" R
   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()
  \% O4 k0 A5 N5 p
6.  高级查询
条件操作符
( H% D! y, A$ V# u
  1. $gt : > " s8 m4 g4 X1 C6 W
  2. $lt : < ' V9 X& p6 X. B8 v) X
  3. $gte: >=
    , \1 a% ~9 N; Y  k, u
  4. $lte: <=
    & y) @3 U5 r8 W  F
  5. $ne : !=、<> % n7 i7 e( @$ S& v
  6. $in : in
    4 l  H# L* i2 ?$ W
  7. $nin: not in 3 W2 ]* g7 c& L& }" r9 y, J
  8. $all: all
      Y" w: ~- k$ V0 t9 q
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

6 e& o7 B# [0 D. y% N, M. n0 o& N; ]1 j$ B5 X
查询 name <> "bruce" and age >= 18 的数据 , x" e0 X3 \+ O) e7 }
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
( b7 K: I2 S& f1 E& R
5 n: _  ^2 [7 Y6 {) j( E4 ?4 L& p
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
+ J# Q# a& Z2 X4 c% r  v  U
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
; z6 }3 O) `9 a2 c; Z

! o( u6 m7 s( _! q) v& {$ Y查询 age in (20,22,24,26) 的数据
0 Q- G4 z- ]% j( @# k: e( I! f
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

& L9 e5 b9 _* y6 ?8 f% N% h) w) U; S9 q/ W
查询 age取模10等于0 的数据 % S, O* H3 E8 E$ H  P+ O) ~3 C
  1. db.users.find('this.age % 10 == 0');
复制代码

* L& F3 z! E2 q6 i7 B4 [$ Z6 X4 v或者 1 F& a0 |! l% j
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

  m4 G, I% F' R. {, r/ p3 p" _1 g
匹配所有
& j9 I% F4 g5 Y/ t
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
0 {+ z5 L; t5 l: r) T4 J
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } . t( x2 `& i0 n
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
: b. b6 M$ Q! r" I0 @0 F4 |, N% c$ v
查询不匹配name=B*带头的记录 * x0 c4 t8 X* c: b+ M4 z
  1. db.users.find({name: {$not: /^B.*/}});
复制代码
4 f4 G2 r# C! X4 Y! F- `
查询 age取模10不等于0 的数据
+ u: i2 x* J$ E8 a  d, u2 {8 b
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
5 c* v; _7 H# ^% d$ x

, o6 u4 I& P, J$ M: F#返回部分字段
( A7 y, D& c8 v/ ^选择返回age和_id字段(_id字段总是会被返回)
7 P  w# F% k3 W7 V
  1. db.users.find({}, {age:1});
    " U  Z5 X. g9 `- W9 J' [
  2. db.users.find({}, {age:3});
    / A8 H( B- W/ Z5 c( |) U
  3. db.users.find({}, {age:true}); ( G( o8 \4 e" R: ^- p1 K) U) L
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
  _+ k3 L6 t! O& }) N
0为false, 非0为true : j: g: n3 M) |0 u: c! n
8 _) R/ G1 G3 i, a1 e
选择返回age、address和_id字段
( \4 e0 c$ h% C4 p+ x* D6 A- ~
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
9 T4 ~% J, }' o4 k4 ~/ {
) O: f; B8 Z& ?6 U. ~
排除返回age、address和_id字段 - k( H% C0 v+ @( j
  1. db.users.find({}, {age:0, address:false});
    8 s9 F" u9 K; E$ e1 q
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
# \& n2 M+ f  k9 h, i) q

. ~$ M# b) s! }; w) A3 d5 b: M数组元素个数判断 0 B, t8 R: Q+ `. |1 S. t
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 1 M5 Q' G  u; r2 t& v
匹配db.users.find({favorite_number: {$size: 3}});
4 J' E3 d- i- t# |不匹配db.users.find({favorite_number: {$size: 2}});
  K! V4 N2 Q8 ^! c
3 q0 c* _# [; V$exists判断字段是否存在 2 ^( I5 X8 D; a. R% v$ ?, M" J
查询所有存在name字段的记录 $ B) y8 b: s. G, H
  1. db.users.find({name: {$exists: true}});
复制代码
2 P9 E: v. q( ^
查询所有不存在phone字段的记录 5 G4 K, Y* F$ h6 ^7 l
  1. db.users.find({phone: {$exists: false}});
复制代码
/ z1 t; O1 r8 x6 V% V/ @
" G( z/ v5 x( D' S& _4 E
$type判断字段类型 # p1 ~4 H5 A* m0 J$ k" ~6 V
查询所有name字段是字符类型的 $ E( J; S1 d) N' k
  1. db.users.find({name: {$type: 2}});
    , I& M* I/ ]) [7 m( ?, ~9 m) |) ]6 P
复制代码

% ?! Q9 G6 d$ h查询所有age字段是整型的 ; K& ~. A6 ~9 n4 M% f3 F* {3 Q
  1. db.users.find({age: {$type: 16}}); & X- P' G; r1 u3 _' a
复制代码

; L4 A" }+ ]+ _4 Q/ U5 Y+ ?对于字符字段,可以使用正则表达式 $ j6 [9 \5 }3 S( b, C
查询以字母b或者B带头的所有记录
  C2 L$ ^; l# h
  1. db.users.find({name: /^b.*/i}); . Z, X* P% e& I7 h6 o. E0 s; e
复制代码

4 T( W! A! i% ~/ E. f3 t3 n( l$ q2 O$elemMatch(1.3.1及以上版本) 1 Z: t. X$ B9 I$ X; B, o- Q
为数组的字段中匹配其中某个元素
8 v* [2 g( S5 D9 {  h0 M2 s' j
  W5 Z4 j+ y9 d# ]Javascript查询和$where查询
/ E  y6 A$ K) @) T2 D5 U2 L查询 age > 18 的记录,以下查询都一样 1 K$ u& I! J; i' v/ q
  1. db.users.find({age: {$gt: 18}});
    $ G+ r. Q4 v. j9 u. C" j
  2. db.users.find({$where: "this.age > 18"});
    8 N" e% a& V1 w5 L3 b
  3. db.users.find("this.age > 18"); 7 W7 H# D8 `  a, W; A
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

" Q: m. r1 j% f$ q2 h: q$ F
7 t+ W% T# A3 J! x8 m排序sort()
6 J: o: p5 y# C4 {% X' V以年龄升序asc ' ?! t) s* \- X# K3 D
  1. db.users.find().sort({age: 1});
    : g( m9 O1 N6 c( p
复制代码
" O6 m$ V2 J$ K5 \# b% z2 Y6 J/ A
以年龄降序desc 7 S. u3 P0 U% t3 }7 V
  1. db.users.find().sort({age: -1});
    2 J. Y2 _+ ^, ]+ o; \; _& _% k
复制代码
, N, n9 D' D7 H$ K: s. g: j- `
限制返回记录数量limit()
( R- s& r7 p% S% w返回5条记录
7 P" G/ {( w# R  b# \( e
  1. db.users.find().limit(5); % z8 @, O5 P, t* E- t& ~1 m5 K& h/ X
复制代码
. y* `' ~1 O7 G- b* h0 _  r
返回3条记录并打印信息
. z' C! o# Z; f* B8 d  c" K
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); " \/ Z+ Z8 M6 b5 ?( C
复制代码
% y2 {$ `* v  W+ f
结果
+ G  I: e: W; C' ]. u7 P. L( m
  1. my age is 18
    1 c  i, B. r  ?8 }- q6 i
  2. my age is 19
      C1 `* d2 w1 k, @% M
  3. my age is 20
复制代码

/ S  f1 @3 \3 O4 J+ |  W  x, K9 s& N$ H" V: d1 ?( L6 u1 }* J
限制返回记录的开始点skip() & k% ?) d. N8 a* C& F, t- V
从第3条记录开始,返回5条记录(limit 3, 5)
( y0 j' ^+ T1 c) I5 g" D' @
  1. db.users.find().skip(3).limit(5); ' Q+ [% g# Q* p+ a1 H
复制代码
, q( i5 j+ U1 Q% c0 n" ~  Q
查询记录条数count()
; Q7 x! e7 E& Tdb.users.find().count();
8 J" w9 p* t% B8 `+ B6 ~db.users.find({age:18}).count(); ( h, U( Q, M( i+ B
以下返回的不是5,而是user表中所有的记录数量
* Z3 H; O" B0 }  ]( B- x4 qdb.users.find().skip(10).limit(5).count();
4 G) A0 x! H2 t: P2 S2 \% t如果要返回限制之后的记录数量,要使用count(true)或者count(非0) / a) {% g: Z% h
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

9 x$ y6 F  o, B; e
, o+ d% t. ~1 N! ^0 I* H1 d( ?% a) d+ P分组group() / n( Q+ U( P1 |4 w! t
假设test表只有以下一条数据 * P2 [7 @# \% j3 N
  1. { domain: "www.mongodb.org" " ]6 z! i% Q+ W! w+ t1 b& T4 K
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    0 ]; x# D7 K* U
  3. , response_time: 0.05
    $ ]+ n& v7 j: Z. l; }1 Q
  4. , http_action: "GET /display/DOCS/Aggregation" ' f% S1 Q! w1 _. b+ o6 m+ \4 g
  5. }
复制代码

# W& K- K& ^8 `" n- k, m使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
* ]. O- k1 @0 O0 @5 i) I' O- y2 a
  1. db.test.group( 1 G' [1 y4 Z$ p. ~3 Q
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    , j. e* t3 b+ O, t" }6 z. m
  3. , key: {http_action: true}
    2 V! g* h. S; y3 i
  4. , initial: {count: 0, total_time:0}
    + y: L- f2 c) R, b/ S( B6 c
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } ( d' _1 J9 e. [& G
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } 9 E7 o* u& O% _# V+ x0 ?! ^- q
  7. } ); ; {# I+ t6 D/ H, f. _' e7 M1 N

  8. 8 H; O" j  e0 Y1 x; M
  9. [
    . e: s* v( n/ ~0 w
  10. {
    & @# V4 }0 q& b( W6 M
  11. "http_action" : "GET /display/DOCS/Aggregation",
    % U: o( A) J5 Z0 L: u; W
  12. "count" : 1, - `5 L& p7 h9 S  R1 M
  13. "total_time" : 0.05, $ P! V4 s3 W" c; q3 o
  14. "avg_time" : 0.05
    / [! s3 u; n  |
  15. }
    5 H9 g6 ?" [. d% F
  16. ]
复制代码
6 i  a8 u7 G8 y9 G- b: V1 o* b- Q
$ v/ [+ q: V* b, {
1 @2 F+ z0 r& Z5 P/ [. m. a! V7 B
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
    / |2 w& [- _- J
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
* m# K- x' w0 J
8 q9 W$ j' n; @

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

! p( j+ u& ^1 H1 r
6 t* [* v5 N' W6 I) y3 E
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
$ }) E) b$ }' _

6 t2 J9 o8 A7 S  v; H
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
7 {, S' ?$ z+ I

) a, g$ @  V+ y# P6 f- F# N! e! |
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
6 B4 W( X2 r) G
6 E7 o3 s. J( E/ |" m
输出如:
  1.         % j5 ^' y5 Y& j8 E0 d+ l: r
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
7 @. X0 @5 o# v9 g' X3 Y% V

; L5 G$ @/ W  d9 b* E
" p* F, Y) B7 l; E  k* B2 ?
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"6 N: T6 s( w: Z% ~: e& J
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"( z. D3 h$ w% O& V
  3.        xmlns:context="http://www.springframework.org/schema/context"
    1 x" u1 W( b$ t( r2 T8 L
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    7 o& v; |, i4 a; P  J
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans$ V0 D! W- ]9 _$ V0 D: P" o
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd; O* i( G; _- r  [8 X7 s1 s
  7.           http://www.springframework.org/schema/context
    9 O% f7 t- w; `7 {) u1 M2 C, O
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd3 l  }* X6 H4 k3 c8 Q
  9.           http://www.springframework.org/schema/data/mongo
    % ?) f1 Y& M4 F0 y
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    & @7 d: b0 J  H! o( u4 g# t
  11. / D4 O# Z8 L3 m  j, _  W* C
  12.     <context:property-placeholder location="classpath:mongo.properties" />9 Y% J7 G: H, e

  13. 3 s$ ]% Q  d* V& M$ \
  14.     <!-- Default bean name is 'mongo' -->
    2 W5 f+ X/ w- V, m
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />: }5 j3 I) F: ]: J

  16. # K3 q7 u& W3 O+ H0 t% d
  17.     <mongo:db-factory id="mongoDbFactory"& d8 S, E2 e/ {2 ~" \
  18.                   mongo-ref="mongo"3 V2 N# G6 z# h. i$ \3 |+ B9 o
  19.                   dbname="mongotest" />' G1 `' ?5 W' z0 T; Y: Y
  20. ; k/ x: x8 R: Z, e: G5 O
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">/ e4 I* ^$ X* U4 b: z6 H( U7 v
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>2 H0 ?+ C- ]' O7 K4 ~  J% L2 t
  23.     </bean>
    % v- {, S7 z3 ~; E$ A6 L( {
  24. </beans>
复制代码

8 a/ x+ |# E. a+ |8 H$ Y! G5 z
" {) N9 Z, M1 d6 @
maxmin的测试
  1. @Test
      f( c* f( _  |* }2 y
  2.     public void testMaxAndMinAge() throws Exception {5 D6 n3 E1 J: |/ o, p; d0 i& c
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);/ R$ r% n% ^( P: R8 C8 I# j
  4.         Person result = mongoTemplate.findOne(q, Person.class);) w0 k; t+ G! U0 ]7 z. }
  5.         log.info(result);0 a/ U9 c. o7 _' w, }% @* b

  6. / W: u  y( x8 h8 G: ~& {
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    ) F3 U" }2 L( G: Q. M" n
  8.         result = mongoTemplate.findOne(q, Person.class);
    3 ?+ D" O& @9 R6 w7 a' u% X+ A& C
  9.         log.info(result);" J2 E$ ~* `: k( H" \+ Q
  10.     }
复制代码
' D* b' s- K+ h0 E- t0 r  d7 ]
. o3 I7 u# q  e1 A; ^& L7 V
distinct的测试:
  1. @Test
    ( D, m5 i+ k1 \; y: L
  2.     public void testDistinct() throws Exception {5 U& M- Y* H9 l, ~) e# t* h3 r
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    2 F7 G8 f, D8 E" v/ q9 N
  4.         for (Object o : result) {; V3 p7 ^" C* L+ g
  5.             log.info(o);
    * H. r$ V8 S! C7 X( l/ ]& j2 ~% \
  6.         }
    & w% u( R9 K/ c
  7. & ~: S1 o; _. }, f0 r' t$ I0 ?
  8.         log.info("==================================================================");3 u5 ^+ |' h' C; G! ]6 y
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    : m. w& Y' ^9 {
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    , v' M- ?  T2 h! u) m9 s* ^, m  w8 O3 v
  11.         for (Object o : result) {
    $ c0 g. i# `' _+ W1 t
  12.             log.info(o);: l6 B" A# b: r' Z7 K7 ?
  13.         }
    0 R5 i( `8 D4 y+ _
  14. 9 E# l9 c* I# c# M# X2 e
  15.         log.info("==================================================================");( Y) B# `' H5 S! b6 n! Q+ g
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    8 N- G8 w% W% n* ^9 Y
  17.         for (Object o : result) {0 k2 K6 R3 S: H: F0 M8 z
  18.             log.info(o);: z- X! w: i4 t" W) V: S
  19.         }" h$ S4 S9 h/ }* ^  |; ?) K6 F( H
  20.     }
复制代码

, B2 g, b; d( h) f
; V5 _7 c/ ]6 P
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    & F4 Q* [, v$ Q/ Q! s: ]: n
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678: ^) S2 w6 J9 `' n
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 4567898 C# }+ x+ Q* \9 i9 l8 {# b
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654& n+ v+ I( i9 U+ {0 a
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    # a9 Y% n; M2 w% e
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo1 {- q$ a$ t% L* D$ o+ d. {
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456, d* d9 P6 d3 K
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    6 ~* L) P/ ], U/ M" y
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    ! H" P. k; Y) z+ v  b. {& z
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    / S  N5 l6 r. R5 a6 S; J
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    # t, b8 @" p; K, }( z  W
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654- s! Y; r$ `* J6 v
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================, x4 w$ v  }$ b; Z6 Q
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    1 J6 Q4 L$ m; [$ J4 V7 p
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb1 c9 d. Y, h1 A
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc6 r# L- S  ~! h, w
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    0 g  z0 `: K6 d7 `
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    ) D# p( [8 Z  @% H& X; k
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy+ R  [; d% j; N0 j( X
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz6 ]/ G2 m/ b# D7 r+ e
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    1 F) G: k9 N/ B
  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
复制代码
* _( Q# a/ |/ G& h& {
7 a5 B8 r5 S4 w" [
这里我要特别说明一下, 当使用了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等信息。

5 n+ X: U; b3 P. Q4 r4 H
  y3 ^" ^4 O8 `5 U4 s  b4 y8 E) C. K% i
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-8-4 23:59 , Processed in 0.064852 second(s), 22 queries .

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