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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:
! W2 ^: g9 G. v& t; R& l
7 g7 I1 w4 ]0 Y( b1 ) . 大于,小于,大于或等于,小于或等于/ U& U% c8 u2 h' K% j1 ~1 _

7 @2 g- _, v) t6 g$gt:大于  o: l! t) U0 A* W+ |4 H: s1 K4 d- V& L
$lt:小于
; X. l, C, X+ |+ W7 {0 n& x$gte:大于或等于- f4 a1 J# m5 b; x
$lte:小于或等于
7 r4 ?/ h/ q& A$ y1 X+ i; Q# x" T5 O4 z, w' h- f7 K$ m0 Q* e2 O
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value
    / b% t: E& Z. e
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value5 n" c3 |4 ^* s) f+ a
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    % L  t# X2 w/ W
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
/ N) f  H) o+ }' y4 U
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    8 E2 M# A; q1 a5 a; D% V% R0 _. e
  2. db.things.find({j : {$gte: 4}});
复制代码
2 r9 l2 Z+ C/ r7 K7 A  Q8 U
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

6 [+ i& u+ \; @" U6 v0 ?/ U
- j" a5 G2 n- S' L7 I1 D
7 L# }6 R! K4 G
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
- |1 P  `3 Y1 z) v
3) in 和 not in ($in $nin), ]- T  Q4 I  w' B) _9 ?- F$ T) m

, ~3 Q( m. s% y. f0 ?! m语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

/ I) q8 D+ Z" T3 K! a& s: U
例子:
  1. db.things.find({j:{$in: [2,4,6]}});; u1 j' a  P3 `5 b5 y$ W$ X+ t3 x* E
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

7 ^5 V# P6 ^" o. G; k4 H/ d

, M9 L' Y3 B( Z6 n! M4) 取模运算$mod
+ B. q7 f9 o1 F6 {, W; Z! f% h
2 d, Y: S4 W. S1 I9 ?3 s如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

. D5 d' ^1 ~0 V& F- W  R
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

1 H$ b( n" y; B7 }6 U6 v

, A$ N9 Q2 h# L4 O1 Q5)  $all2 I% x; b8 J$ T9 w8 y* i
2 m8 Q/ O, ?# t* {  {# A
$all和$in类似,但是他需要匹配条件内所有的值:
6 W! B# Y3 z8 ?$ L' G. o
6 [! u$ Z/ R; R4 ~# B! s如有一个对象:
* A6 m/ u. n0 N6 V4 M. O
  1. { a: [ 1, 2, 3 ] }
复制代码
2 h) L& C- [2 S" Y$ [6 {& I5 C
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
) q' ~& F! f4 ]4 [; ]. m
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
9 _) Y$ \7 s: V5 W/ r& r5 x6 g+ f
/ q1 T! c; U% R) R/ \
6)  $size$ j4 O; d) x$ N$ i( [7 c
' o( t# D8 w: r1 ~. f, }! L9 F
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
! O1 K. _+ q9 [$ ]3 }* j* w7 j
2 T6 V" E! j8 e+ {& h下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
7 {% {- A8 F0 g8 Q" |' g* 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.

0 K1 B9 \0 r* F( L) V5 u
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回  w. C0 u7 b& G6 d+ Z8 M5 M; ?
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
$ d( s8 K, n1 O* U/ _
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    9 Y. ~) b8 M, G6 c
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
+ @; C6 C& [& f. S0 E0 h/ |
9)正则表达式, D$ ?4 s/ D" [8 S; S+ R
. V0 D  `  i" Q3 G' y' \; D
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

, _# D+ q& I; P% S+ Z- i" L# w
10)  查询数据内的值" y! R, L0 x3 `7 G( b
/ ^: O: C  _! {; R/ k) ]
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
% I% b' }! X9 ~! f, G) W
11) $elemMatch- _% A5 e, f: W* [1 x7 N2 A

# E8 M& ^/ h8 W0 I1 F  b; O如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    . |# x; C. R$ K+ d
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  9 p! }* {! w6 K1 R  F
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    " `$ e  p/ y5 C1 @. D7 t' S
  4. }
复制代码
- p7 g/ S8 S+ H4 Y: k6 `
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )# ?9 N# J/ Z# K1 q6 g" u7 H! P
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
/ o1 `! c9 D$ M3 B, D
' |3 s4 y, u* @+ `5 m& {. A0 k$ y; ^12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
( q; G! a! a4 ~+ j0 C& {$ _3 T: C- X$ z
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

" S% g, b# M7 N7 ?+ }& j) X
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
+ ?9 L- k( }) X) X7 @* z. n
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

8 \( y' C$ J. m
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

) H# }- S( Z, H) x
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
' _7 W, n1 h3 {9 l5 c8 g" L9 g5 Z  U0 p
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );, k: k5 v: T. o- h! j
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
4 Q$ Z  \, P) B# s9 {6 w3 I
mongodb还有很多函数可以用,如排序,统计等,请参考原文。7 p' O1 t9 C5 n  V2 A1 E- J
% S# u8 ~' d4 L  J* [* q
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
8 c! c+ x8 C. [
+ R- P2 Q1 A0 @: H0 N+ q. z! ihttp://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions1 P3 Y- T  N- w' q: @3 X

1 c- i+ r, |$ K8 G版本二:
! f9 e7 O  \' D8 K
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

3 H7 t% |3 d4 s1 ~5 U
  1. use admin
复制代码
" T& M( {& \  W$ M
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码

7 [% i9 z# w6 C! ?$ w% c/ A( Q' r
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
7 Y0 ]6 ^) R2 f8 m+ i
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
7 r  r: \& b/ q  s' B+ @! `! h, b
         5. #删除用户
  1.           db.removeUser('name')
复制代码
3 q/ e0 h; e4 ^
         6. #查看所有用户
  1.           show users
复制代码

" V1 d5 c$ @& j' H% Z
         7. #查看所有数据库
  1.           show dbs
复制代码

2 C/ h3 \9 e6 D- o% i- W' K$ f$ U
         8. #查看所有的collection
  1.           show collections
复制代码

0 z4 \1 f4 |1 r( l+ F  \
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
( Y; @- A& ]) H4 e0 Z' X5 q4 @
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
: E6 n% ]. T* `0 v
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
6 E- O, G- Q* C4 Y+ l$ L! l
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

! ^+ Z: z3 ?# L# ~
        13. #查看profiling
  1.           show profile
复制代码
6 G* W5 ~: M1 {. I& M* i& w$ P$ _8 u
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

+ |4 Z5 G5 A5 u2 W$ A
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
. u- t" H* f1 h6 w' F; ]
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
. u% y( p9 M# \8 h
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
. C- T$ H! G8 o2 N. Y
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
1 y, Z" u  [) Z0 K- T
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

" Z7 X, x9 n, g* f4 h
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

, ^: t( e& x- c. L# a, {
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
/ u2 }- r% b* A# l  o0 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()

8 @3 m& {/ K2 m- Z: j: c
6.  高级查询
条件操作符 - e2 p6 y" G& W
  1. $gt : > ' C; j! l# }  n6 d
  2. $lt : < + K5 @. Y) T8 v' n+ _  e' a% {
  3. $gte: >=
    8 Y8 j0 k3 {6 r  \: v. W* I" l: q
  4. $lte: <=
    5 }8 U" u; G" k  r* m; D( _( o& G* j
  5. $ne : !=、<>
    3 U$ g! {3 i0 [% M6 s
  6. $in : in & ~( ]. a$ m' c2 z+ u. P
  7. $nin: not in
    7 V" W9 T* u$ J4 X/ X" u
  8. $all: all 8 \  ?- {1 F& |
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
! {( i+ t" s+ }6 c

, o9 P1 _  r% ]4 g6 F4 {3 I查询 name <> "bruce" and age >= 18 的数据 . n* W; r6 O6 k6 `
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

1 p# f) ^) e2 S! p6 v
+ ]  d; f. G' M6 C* ^, O查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 ) R: c: c9 v: \5 O7 L( N! `2 j
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

- O6 w- ]/ \6 q6 ^: g5 E$ M# C7 h8 C' R/ x! P9 L8 V, P
查询 age in (20,22,24,26) 的数据
: d6 f  W; S2 C4 ]. W- z
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

: @" d" x$ w; T
6 i+ B; A7 I( |1 x: p) w# p% L+ Z查询 age取模10等于0 的数据
% u( L  r! S6 R9 b
  1. db.users.find('this.age % 10 == 0');
复制代码

( p$ w1 k$ [8 `$ h; D5 ?' `6 v4 u  T% k1 H或者
- _  Z4 n" D6 C
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
) O9 Q8 G% ?& U: i
0 z% m2 e0 e4 f7 ]
匹配所有
" c% C5 G8 h# ?  B: x3 M  x
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码

% X! m' z; Y9 o1 d可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
7 l# n, u7 y5 g, p. T; ~可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } ; `9 g0 p' z2 w- d. c3 ~3 i
  x! r7 @) \2 X7 L
查询不匹配name=B*带头的记录 , @2 m3 S3 y* h$ [# l
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

9 C& @4 z2 q4 N% o% P查询 age取模10不等于0 的数据 * H! `; U+ y" j( |. q: W; q  \
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

* Q6 k0 ~7 _% Q* o7 V/ U
6 X- h1 m  W/ A; ]#返回部分字段
8 F- Y% W0 \' g选择返回age和_id字段(_id字段总是会被返回) 5 b: s4 w. m( j5 j2 @$ f8 W
  1. db.users.find({}, {age:1}); 4 W1 B3 B& c8 y) R6 e! i4 m- n
  2. db.users.find({}, {age:3}); % x! p( U) v- H+ G& b. \
  3. db.users.find({}, {age:true}); # s# m9 {+ C4 r6 Z) N8 {+ F
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
4 n: B5 u* N* D6 D
0为false, 非0为true 8 S3 O  N1 x$ p5 U9 a, g: l

3 L5 I9 i1 K/ S选择返回age、address和_id字段 # Y+ ?! T2 M3 Q
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
& X9 a4 E4 v  v. w: H

0 m+ s6 R0 o) d2 K- O排除返回age、address和_id字段
9 E8 p1 [) U1 ]* z3 I7 X) T
  1. db.users.find({}, {age:0, address:false});
    . w2 K2 |- Q4 w/ d/ k
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

( F% w5 g  f! N
! N) p6 j) H8 ^2 x! P! T( s数组元素个数判断
( f1 q% K" L2 C& i: ~! D! ]对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 8 W) f/ i+ c* g$ g) e( z
匹配db.users.find({favorite_number: {$size: 3}}); % L8 J9 G# Z& Z) l( o1 F
不匹配db.users.find({favorite_number: {$size: 2}}); 2 ]/ R6 ^0 h- D5 L$ G
+ @: c, q4 a( W1 @
$exists判断字段是否存在 # K) S! k9 H7 Z/ ~8 B
查询所有存在name字段的记录
! ~! M$ b' X/ l; D
  1. db.users.find({name: {$exists: true}});
复制代码
4 ^0 }" F, i  b: @$ @" ?* A% c3 q
查询所有不存在phone字段的记录
2 o3 H+ l5 W4 i
  1. db.users.find({phone: {$exists: false}});
复制代码

# T- w3 q% w5 a2 e" `$ R& R. W6 K
, x2 ]- q4 d- X5 U# ]' V4 @$type判断字段类型 4 c: D' E6 L# |
查询所有name字段是字符类型的 * P+ [% k, ^4 o  f4 |/ ]1 ?
  1. db.users.find({name: {$type: 2}});
    % H7 K2 Y+ V4 ^# H& U3 l' v
复制代码
7 ~! z( J3 X: Q2 T" a( R
查询所有age字段是整型的
* ~' N/ o- |* ~: \# o0 ^( f
  1. db.users.find({age: {$type: 16}});
    + a5 Z7 Q& ]2 `; t9 t, X+ D, L
复制代码
3 f' O6 Q9 u% m% ^. X$ J
对于字符字段,可以使用正则表达式
9 W9 h. X  m! q: W# T4 j3 j查询以字母b或者B带头的所有记录 $ z! w0 j- q( @; a2 t
  1. db.users.find({name: /^b.*/i});
    " W/ m& S3 k4 r/ e: s" d/ v9 w
复制代码
: R+ G& u7 D+ \- j) }2 \6 ?
$elemMatch(1.3.1及以上版本)
) e& N8 r. Q" q' \为数组的字段中匹配其中某个元素 4 [) y! K- U( y1 o% [% b+ P
: v% S; p0 B1 q: N9 Y( L2 g9 T
Javascript查询和$where查询
8 w) D8 @4 p: |" S" D. i( l查询 age > 18 的记录,以下查询都一样 . _6 A% ]1 ^  K
  1. db.users.find({age: {$gt: 18}}); , j- y+ {5 ?! y+ I) Q7 T% T* c8 L
  2. db.users.find({$where: "this.age > 18"}); 1 Y! [/ D% v+ o' h: `* O( I& z8 D0 p
  3. db.users.find("this.age > 18"); 9 u1 b1 B9 [$ t4 e% W5 M* N
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

, L# \" X: ?' g8 m4 ?0 v, [2 u% ]+ X$ j' N) k. h8 c. P9 c, ?: v$ U
排序sort() 9 P9 k& E) F3 P
以年龄升序asc
; ~3 L! R' \1 o) l8 U) f) F
  1. db.users.find().sort({age: 1});
    ! l$ q8 M$ G6 D7 X3 n/ `% c
复制代码
" j6 Z: h* k* K) h, h
以年龄降序desc
1 {% v# \2 c4 I$ t
  1. db.users.find().sort({age: -1}); ; Q( U/ w  R/ B' T5 p) K6 E. `# ], t
复制代码

' v: ?5 f* _" f8 O5 ?4 }1 \  Q限制返回记录数量limit()
' J; [# s) t4 E返回5条记录
( s7 i9 p# c: q2 b
  1. db.users.find().limit(5);
    - J5 C5 Z' I8 q3 f; ?" Y8 p
复制代码
8 P  u: r, M( y8 t8 T: R3 Z1 U: d
返回3条记录并打印信息 8 v( t$ d4 R+ R) W8 V" i* v) E
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); - u$ L  Y+ F. c
复制代码

2 V: ]9 t0 V# t5 ~6 F0 P结果 0 D) E# e8 {! V1 J+ ?' X! w- L- \, C
  1. my age is 18 1 e: s/ P6 j! r
  2. my age is 19 " y0 ?' l: F0 I! z) T. J" t) S
  3. my age is 20
复制代码

/ e( Z& t: \* V' L9 M' _* y9 T
# S" w( j2 A2 r3 J& Y0 c; y& p限制返回记录的开始点skip()
# ^, h* H0 ]/ I7 V* U! }* w$ @4 B; ?从第3条记录开始,返回5条记录(limit 3, 5) / }2 \& H9 m+ F2 H
  1. db.users.find().skip(3).limit(5); 6 b' z, A+ ~* Y
复制代码

9 H& o; O/ x/ f3 f. O8 V查询记录条数count()
; @* c; k! f4 r, |, kdb.users.find().count();
$ c6 A+ N$ s: d  M% bdb.users.find({age:18}).count();
: @, A/ s# Q' |2 O8 I- ]以下返回的不是5,而是user表中所有的记录数量
+ z+ Z. e3 d  s$ T; B+ ldb.users.find().skip(10).limit(5).count();
$ e! s6 u, Y( ?) U如果要返回限制之后的记录数量,要使用count(true)或者count(非0) # j/ e$ k, F: K1 ^9 d
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
9 ~( z( H* H+ w/ K  f6 [  A; o+ @

! M2 V) I) C# ^- |- o9 ?5 s4 h分组group()
% j4 l, l! F$ F9 Y8 y8 I, y/ r假设test表只有以下一条数据
/ _4 a# ]* [) C3 L1 d5 q* h/ r0 J" I7 o1 f
  1. { domain: "www.mongodb.org"
    - ^3 T0 L$ D8 N
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} ) P/ v/ @. I3 w  ~
  3. , response_time: 0.05 ! \" r) f8 [/ V+ s% A
  4. , http_action: "GET /display/DOCS/Aggregation"   E0 T- J+ c' L
  5. }
复制代码
4 w9 U$ u$ d. Q, P
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
0 A2 _- ?" }! _; R8 D
  1. db.test.group( & N4 i) q0 ?7 c# w$ [3 D
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    & N  e* e: {- E. a- }8 N
  3. , key: {http_action: true} . G4 m" z% k3 p' f0 g
  4. , initial: {count: 0, total_time:0} - Z8 }: C9 k6 Y! ^# b! c" o
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    9 B& M( u" N/ w, }
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } 9 B4 y4 P; T6 O' ~
  7. } );
    " X4 P5 E: \* h
  8. 7 l- w0 ~2 z: f9 d3 P. x# M$ s
  9. [ 2 H$ `% v& g- o& {$ F
  10. {
    5 s( t0 [' i5 |3 T
  11. "http_action" : "GET /display/DOCS/Aggregation",
    + g2 ~; T$ H6 O. j0 Y
  12. "count" : 1,
    * D- u3 J- I  [6 @# O7 a& r  l( ^% _0 ]
  13. "total_time" : 0.05,
    . t. E  q+ Z  _" c6 L4 b
  14. "avg_time" : 0.05
    5 @, C; x2 y. m
  15. }
    . u( ^2 u# @: J0 c
  16. ]
复制代码
* E1 N: n1 `0 H

9 z3 J) H) [9 [* O& S& Q1 ?) u) Q0 V+ ]3 @# c2 H
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
    . |) ]+ B. J' j: X' i+ n
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

) ~- ]. o" V/ V( m" X/ U" v7 {; Z2 A' i: ^# a9 b0 W2 v
- C4 d$ j  T/ O. n% t
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct1 d" s( U9 Y' ~' l- a3 U) p- u) Y
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码

& I& v- i: ?3 L8 o( b- Q5 l5 y8 ^
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
( f5 H# H. E+ ~+ k5 G6 D
+ R  a: D2 j" ~. b
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
4 P; r+ x0 W6 K# ~; \6 z
5 y* C& t8 {6 G6 M' ?9 @
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
$ j" R! E1 s& B+ b1 j# u( ~
4 f& w; U& e8 e* X/ [, B
输出如:
  1.         
    9 E! T1 }+ G: E) u
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
' d; q0 ]: y% ?% U5 k; y

3 A; `6 b+ }7 h( r3 `& ?6 V0 R2 g# c: A9 B: _
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"
    3 c( L: p2 o# Q# }
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    * o' t) X8 B( F/ q( B$ |6 r
  3.        xmlns:context="http://www.springframework.org/schema/context"0 X# m& Y* R# ~) S- _
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    + `, J9 j6 e$ @8 K: T- }
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    ; r0 Z' a3 o' k4 a5 T
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    + H# X8 N1 h, H/ t4 L2 ]% n9 u2 }; @
  7.           http://www.springframework.org/schema/context
    6 j4 o( E( f" b. l; q$ x+ E
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd; H2 m! v8 E9 ]- R; o3 H
  9.           http://www.springframework.org/schema/data/mongo
    4 p7 ?) D2 R5 o5 ^- f5 G; w8 y& s
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    + O# i, k5 ]/ s4 h( V- C+ H

  11. $ e9 l  A# b3 P- y$ O! c$ _0 a
  12.     <context:property-placeholder location="classpath:mongo.properties" />$ ?: Y% J- E2 J% g
  13. * D( [1 w0 n9 f7 i" @6 `
  14.     <!-- Default bean name is 'mongo' -->
    ' X8 ]7 w' b, h8 `5 v* Y3 m% g
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    3 T6 B' g5 G* o8 ^

  16. / U; d4 f5 t$ k' m6 R: q- {
  17.     <mongo:db-factory id="mongoDbFactory") G: d, x$ a2 X
  18.                   mongo-ref="mongo"
    ' l6 i/ a* D. H$ X# M: W
  19.                   dbname="mongotest" />5 B# z$ {& g4 d& Y

  20. " U7 f4 |+ J, P& Y, o! X
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">" P; U2 N) @  C1 w
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
      F+ U4 V+ S, y8 |0 w$ V& q
  23.     </bean>
    + H: M, G& a0 O5 E: L
  24. </beans>
复制代码
# X$ O# G0 M9 U% o$ b

1 g7 Z9 L7 R) b( ?
maxmin的测试
  1. @Test- B4 z- W/ p5 l
  2.     public void testMaxAndMinAge() throws Exception {& J1 A+ a% ]$ k% C/ p
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    % r5 t) S& h$ l5 M$ K
  4.         Person result = mongoTemplate.findOne(q, Person.class);
    , W4 ]. l5 f, Y
  5.         log.info(result);0 S2 L- P. ^9 q* `4 e1 G$ H

  6. 3 U8 x4 v. K. N2 F
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    0 B5 ]* k3 ]! |" O( P8 f3 F  Q
  8.         result = mongoTemplate.findOne(q, Person.class);3 z8 C  `2 `% t, S3 M
  9.         log.info(result);% K& _6 `" n  G6 w4 j
  10.     }
复制代码

, U" F+ V: _/ a/ v" R$ ~  X; Y+ C4 `# c9 c1 \; V( H: Z  @
distinct的测试:
  1. @Test8 f+ A6 B& {( r+ p, o# j. x
  2.     public void testDistinct() throws Exception {9 [& n1 L9 R0 G) I8 v+ n
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    ( f1 z) f. S! A/ N. j0 {
  4.         for (Object o : result) {
    ; q& V) J' t1 }) H8 _% b+ x. U
  5.             log.info(o);- i9 t0 q6 f1 s- j# e$ C8 y! y
  6.         }/ M$ d) k8 X  N, V9 n8 s# r
  7. ; O  i  \) ?; F2 I" _
  8.         log.info("==================================================================");; X, e, i  b* A1 ~9 [
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    1 T1 x) Y* s. U0 k
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());" c# L+ x/ y) y
  11.         for (Object o : result) {
    ' U' K+ v- y0 L1 n
  12.             log.info(o);, R. r& d7 `$ ^8 w5 \  {9 S
  13.         }
    , j5 r. i. C( @# U7 Q6 P7 Z& b
  14. 9 c: I, T2 l- C  [$ e( d
  15.         log.info("==================================================================");$ B* j" S( U0 h. h5 Y  P
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    ( B' e/ ?# O: {3 G$ ?# t
  17.         for (Object o : result) {; f+ ]& V$ X( k" L% H  p7 B& L  w1 Y
  18.             log.info(o);4 U9 X/ V% S3 l) B0 c0 c
  19.         }
    7 @+ M, {  _8 N4 B5 q7 [
  20.     }
复制代码
$ Q1 x' Q$ P, U& Q$ E/ U0 g7 x
& Y( O  ]2 r2 t9 E. G( F
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    % j: _6 Z2 m6 ?- I- A6 B
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    8 E# }: t+ s& a2 O( E2 k% H& r0 ?
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    - [6 g3 |6 X& B  c, U/ |2 A7 c# _
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654- J* q: P4 R& Y  d
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    7 [4 ]/ l' ^8 v) d' A" @7 Q
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo0 u3 S$ R# ?1 _. G$ L/ H( u
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 1234566 q* G) K  F. J3 o6 V/ \2 u8 K
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    " Q  w* }6 p, S/ {. ]+ n, O
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567  z, t+ k  R. c2 S5 D! _* e
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678- s( e( O6 b; R, T4 O8 M
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    0 {8 [% i. \, k" w
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654/ c8 ?! A4 c8 T  w  t
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    $ B  U, @3 q# A; F. E$ P  G: r: M
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa) I6 V6 P5 q9 Q" l- r
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    , n( Q5 O: g8 I
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc7 b  V: M: T( n5 M
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    $ T0 w( u% `. \6 X
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    # n/ B9 h6 a) n4 S
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy7 m2 p. f% m3 s3 z* l
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    , `$ O& a" C- u' ~
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    3 x. \0 B9 ]/ w
  22. 12-22 14:13:45 [INFO] [support.GenericApplicationContext(1020)] Closing org.springframework.context.support.GenericApplicationContext@1e0a91ff: startup date [Sat Dec 22 14:13:44 CST 2012]; root of context hierarchy
复制代码
$ \2 z" W" m( N5 E0 _
3 O: i8 S, h( g: a
这里我要特别说明一下, 当使用了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等信息。
: L: \  _/ w+ c! P" ?
9 m/ E% k+ t( z$ X
! S5 }& r! g2 A5 d; ]
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-1-30 09:47 , Processed in 0.069299 second(s), 24 queries .

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