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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:; @. S" L3 {# n0 M: K" q

6 o4 j, n9 E3 h6 \; ]; a$ x1 ) . 大于,小于,大于或等于,小于或等于* s0 e9 X  ^3 t# {% j  g2 W

; f) O- b9 l8 c5 U; [( K  _3 e# J$gt:大于
1 Z, N- `6 s! Q  W0 V$lt:小于" w# D  e5 ^: z( v0 [1 Y
$gte:大于或等于
  l! W* W6 I; c& I3 E$lte:小于或等于
) R/ ^! a; k7 s7 O, L
8 r4 Q. L$ A2 W! F  {7 [9 @- v例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value
      T) S4 k9 g9 t6 @* n
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value% ^2 l3 f5 d6 }/ N5 |/ [9 P2 S$ [
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value/ j& C: L" b+ `- r$ M
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

. d8 W8 M, S' Z/ m8 F! l
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    - F# o/ j* C2 Z; E0 ?# x
  2. db.things.find({j : {$gte: 4}});
复制代码
& u' y5 z) V/ D. [
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

0 X6 U8 u. w2 m- w- Z" E% \% K
* m: i3 ]6 I5 k$ Y4 h4 I& I1 B
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
7 x9 R  {$ ?2 [+ @# B, f
3) in 和 not in ($in $nin)- a0 f0 M2 e- h9 c- c& U5 ]

4 k$ d3 |  c3 ~语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
& Z- m9 }: b* x
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    ' Y, x' ^- M5 S5 M
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
+ J( @% v# J* n4 }1 t" e, K9 J# F

# n+ c& K  a+ q$ b0 W3 [+ k. c4) 取模运算$mod2 S* p. t( `7 n. W" b
! E& x( S2 X& z- |  O; F  h- X! c
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

4 {/ i2 P0 a6 z1 \$ ^
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
, t4 g; O! C, N0 Q4 q  d& c

; t. F7 F3 V) i, \& E- A5)  $all# e5 F6 O6 [" `6 v# c6 j

, O) \5 @& r+ v2 s3 T$all和$in类似,但是他需要匹配条件内所有的值:
6 ]% S( Z# i! H) x4 u: G
# z* m9 p9 g: a7 s& [如有一个对象:
8 I& F* a& V# y1 k/ ]* P6 t
  1. { a: [ 1, 2, 3 ] }
复制代码
  z- X% B( w+ t: Y1 p  [
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
. I) A, p$ k  X$ S9 g- P- U/ [6 b
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
- y* Z7 M: V" h3 p- `" M! H

" @1 {  v3 C* l) I8 q6)  $size4 _9 s9 n! o; [& a/ x/ [0 ?: S. \

4 m0 \7 z) Z4 i; q8 F$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:2 ?, X' s! O3 k* k/ \) K

1 s& c: b2 y" I0 H  w6 Z5 g下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

. V; _% H% Y6 U0 j
官网上说不能用来匹配一个范围内的元素,如果想找$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.
; C. F% ?  G) O) b9 Y3 k& o
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回5 }. g5 i) f: p6 C, z
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
9 u6 v) Z- ~- f4 x3 r
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string9 ]* Q# Q. Y0 b( G+ G* P) {" K
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

7 Z) B$ [: Y: y2 _
9)正则表达式
' F& O& _, A3 A1 p, K/ N" c8 i6 V! l9 {
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
6 D+ f0 O: g1 k! i. ]
10)  查询数据内的值  }5 c8 G7 u; F* a

! Q( o9 f. x1 G* e7 k. ]下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

1 f) G  D: v7 e0 z0 i
11) $elemMatch
: \8 Q8 t9 Z9 l; e4 K1 ]$ M
! C- ~. @6 b9 H6 U* [2 {' F0 \/ y0 k如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    , o; z: e  I4 y9 A/ Y' m4 @0 {
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  ( ^; c: \6 j; @  Y6 \0 X
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]" \; W& U+ o' t
  4. }
复制代码
. p, `' l1 j; }# J5 \9 i
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
: G& X& m4 T! f2 l" @4 j
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
: [$ Q5 l9 L8 L. g) Y" ^1 ]. e# w1 ~$ _6 A
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
) f2 D9 s# K* Q: N
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

- x' z/ |( v' t& Z! l
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

+ j$ H9 ~; w( T
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
+ K! M: K9 p+ ~6 k7 ^
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
. `) U6 ~- D2 L
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
2 L) w3 u: V/ [0 z% O  _
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );8 c0 G9 `  h, m1 }
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
3 w% C$ q2 ^  e. o$ L5 G
mongodb还有很多函数可以用,如排序,统计等,请参考原文。. B+ b4 ]- L. v7 M8 w

* Q, V6 T9 `# d) {7 y' B+ pmongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
0 f0 D- }; P  E7 i, _, A/ A$ U8 Q3 e: K8 l, Z$ y2 M
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions3 f' ?. J7 I4 _, m# J7 @, H7 M% w

. c( O+ G  C; l, l; l) D版本二:6 S, v' O# T& j" T% m6 y0 l
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
- B  a# x3 ^2 N" r! p" Q7 m
  1. use admin
复制代码

3 \( D/ h3 X" L9 H6 ~) \
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
2 y+ O/ S" L' K2 M; e& i  V6 y
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

8 v: j0 g+ g- z' h& g: }
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
, R" D. Q" X8 N. c
         5. #删除用户
  1.           db.removeUser('name')
复制代码
3 `6 t, k7 Q9 h1 W( Y: L
         6. #查看所有用户
  1.           show users
复制代码

1 i  @+ V- V' o6 ?. Q# b" \% F* z; h  z
         7. #查看所有数据库
  1.           show dbs
复制代码
# C# Q4 K: |* B! P; z+ W' I3 \
         8. #查看所有的collection
  1.           show collections
复制代码

% W$ t: q) s, o, O
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

$ N, t7 v5 q8 S3 R% F% O
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
9 t6 |3 E8 l0 U) N: R
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

& l% e% X: }2 m
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

, t2 I8 f1 Q0 l6 }* S8 ^- T
        13. #查看profiling
  1.           show profile
复制代码

% `. u$ }: K+ N4 ]
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

1 }! w5 {4 y" f1 h
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

* }; G5 O+ }# r( o, M2 i1 j
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
% ^5 ?% ~8 K1 {7 I
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码

+ F. B% s4 N8 s8 l2 _; x7 g; g
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

# o+ e) X& ~" [; G
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
! i8 h, L1 z7 W% l6 \
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

' B# ^* X; z2 p; m: D
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

1 e0 f. w/ U2 h5 F% M3 C7 i' ]
   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()
0 k, @2 P+ }5 X- v7 q% ~+ t: N  n
6.  高级查询
条件操作符 8 c; ?0 g% s/ C; v1 S2 n
  1. $gt : >
      c3 h1 w5 x8 o3 d# F
  2. $lt : < 5 `7 B3 Z' P" C) \5 s
  3. $gte: >=
    7 [* [: S7 @& T" @2 l
  4. $lte: <=
    9 T6 E5 W0 `5 {9 s9 `$ J1 |, `8 {. W
  5. $ne : !=、<> 5 J8 u3 H' j# d9 ^
  6. $in : in
    4 w5 n/ W' \5 l& c: o5 E; _
  7. $nin: not in * ]7 J% f1 {" U+ z# j/ B
  8. $all: all
    , N* W# M/ Z) K: W. u7 A' Q( n
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

( ^; r, W3 N2 e0 R3 ^& S  T! y  E8 [# y4 C; p9 t. O
查询 name <> "bruce" and age >= 18 的数据 7 J6 z: c$ y/ h( u' `8 A- v! r) j4 h$ G
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
! I/ U$ s" C9 N' F8 e0 r

8 q$ b  t0 o' Z% s0 L查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
( g" E  b  Z7 k
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

: ]6 M9 Z) Y& V9 ]) ]* N' h
, U( o- v9 d& Y9 G- m  P5 c" d7 z) w查询 age in (20,22,24,26) 的数据
5 u# v: i# x8 ]+ v' w4 J3 ^
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

) {2 T; n, i) m5 |8 [8 d
' L5 w7 Y& C  {5 y查询 age取模10等于0 的数据 0 ?# L% o5 j. P! o! x; O% Q
  1. db.users.find('this.age % 10 == 0');
复制代码

/ n! z* H/ {" o4 H/ |或者
5 J2 l, U  c2 _" q0 [
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

" N& |: N! W$ T4 {& w* R8 O' r& L0 e
匹配所有
3 {3 B$ Y, L2 Z) z  }
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
5 B, [3 U- _( e  o- d$ Y- p4 T/ N
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
" q. W. d7 S: J可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } ' K4 @* f8 W; K" o% |" |

: |4 K2 c3 v1 j1 ]: B" H查询不匹配name=B*带头的记录 4 y7 K. V& k" Y
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

4 p3 {6 O  E4 J. Q: {* U查询 age取模10不等于0 的数据 4 O; J" e# q7 [. ?+ y. R
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

/ I4 F; S9 e5 |
9 b7 W5 D/ f+ J7 o#返回部分字段 / m7 {: D4 F; a- @% B  ~6 j
选择返回age和_id字段(_id字段总是会被返回)
! @/ H2 f- M4 W1 |# s3 b
  1. db.users.find({}, {age:1});
    " v# A/ d6 m6 a) u
  2. db.users.find({}, {age:3});
    - y) P$ \% y1 X; q& Q
  3. db.users.find({}, {age:true});
    0 d7 A* [# f/ A, {. ~  f
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码

6 z! Y* A, @  }% c3 V( V9 D+ |0为false, 非0为true % m  C/ R" a& @3 ~6 P" b
. A: ?# H- i$ ~; P
选择返回age、address和_id字段 " n/ t6 \, u9 C* V1 R9 q& L
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
/ ~6 y. ^6 w& V8 g+ u% J3 [

# y9 T: `" ~# N排除返回age、address和_id字段
# L2 D* o* n3 c' V7 l0 {5 i' l
  1. db.users.find({}, {age:0, address:false});
    9 T/ J+ ]' K& x0 l. r  d% C
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

* l: i+ ~2 i: V  t( `* h) n
. o4 F. J% t) r9 |, v8 O. R数组元素个数判断 . ]6 d' i; s) b4 C
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 ( i/ r% z$ J) W+ Z$ O
匹配db.users.find({favorite_number: {$size: 3}});
: Q+ j" v% q( x1 |9 i4 U不匹配db.users.find({favorite_number: {$size: 2}}); " i/ x8 B8 b, [! ^9 S, s1 B8 |

& _/ |; E% X3 O# z: D6 L$exists判断字段是否存在
7 O8 _4 |/ ^9 c查询所有存在name字段的记录
) m5 o! i5 u4 J3 d$ I
  1. db.users.find({name: {$exists: true}});
复制代码
% ?% D* e4 L- S; n
查询所有不存在phone字段的记录
$ ?" m' C! P2 j  C- c
  1. db.users.find({phone: {$exists: false}});
复制代码

7 l- r/ B' n+ m) d# F* j: o& {4 l7 X0 `; o! o8 E
$type判断字段类型
, |0 o( F/ F- C4 d& W+ q2 C, J查询所有name字段是字符类型的 # s3 [0 h1 ~6 }4 P6 Q* F
  1. db.users.find({name: {$type: 2}});
    + m! f& S  f: P
复制代码
& Y. K) p( |9 T5 ?4 ]
查询所有age字段是整型的 ( X4 u, K: Z! r, o# w! j
  1. db.users.find({age: {$type: 16}});
    & e2 _% Z) ^" v$ S. `
复制代码
# T& x2 ^( g* I6 E5 |1 R& S
对于字符字段,可以使用正则表达式
$ Z  M( v! {  S; S; ^1 q查询以字母b或者B带头的所有记录 2 H: f1 p; N" G: V
  1. db.users.find({name: /^b.*/i});
    3 M1 T0 V' r1 \0 F+ z" Q7 E
复制代码
0 l' G. B4 c* d' H
$elemMatch(1.3.1及以上版本)
: J& U3 ]3 c3 a为数组的字段中匹配其中某个元素
5 L6 O/ r2 X; N# s3 h
, o  a& ]& l; [$ J  }/ G3 }Javascript查询和$where查询
; C2 N8 c7 e+ ]" a5 j; y6 J' Y查询 age > 18 的记录,以下查询都一样 / K0 {. }1 X; `" Q8 y7 ?
  1. db.users.find({age: {$gt: 18}});
    2 h: p) F( R2 t9 k  l" B  v
  2. db.users.find({$where: "this.age > 18"}); % Q0 {. a9 t; `7 G. ^1 C
  3. db.users.find("this.age > 18");
    / ^6 o1 n" `2 I$ q& p
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
# \; B6 @+ ~8 Z3 `5 q% k
1 x& V3 J2 }" \( u" j
排序sort() / D' s; k/ Q, C2 z
以年龄升序asc
- a6 V3 y# m( W2 V3 M& u5 w, l0 v1 Q; J
  1. db.users.find().sort({age: 1}); - K. E5 m, B2 m8 e$ N( h  Z
复制代码

2 W3 @$ m5 \5 a$ A' f以年龄降序desc
: v% q% f$ R: e* Q
  1. db.users.find().sort({age: -1});
    - o9 R+ g2 F. R! {! `
复制代码

1 `! i+ ?, Z5 }; F: g限制返回记录数量limit()
8 G# `4 a3 C% H+ i5 T. D( j返回5条记录
; `* ]6 I$ g6 [1 n. S" g8 v. a
  1. db.users.find().limit(5);
    0 s; {. x7 u2 y1 R5 N" b! S  ?
复制代码
: d3 o5 f" f7 V) C0 {# V
返回3条记录并打印信息 - d. d- I6 m; o: e" X- |
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
      Q. A2 U5 J2 o
复制代码

# T' l' \4 w- K% x结果 & B$ E# a* l) v, z$ f  c1 K
  1. my age is 18 - u( _  n! F) N' e8 j- d) O) D
  2. my age is 19
    " [9 m# @" a5 e! g
  3. my age is 20
复制代码

$ a6 L) E$ J5 X5 f/ X! Z0 _5 w' V1 T; _6 o, r
限制返回记录的开始点skip()
+ b* K7 J$ P% k. H2 O5 h8 l3 L从第3条记录开始,返回5条记录(limit 3, 5) 2 O( G. q2 x$ T: M; L  Y
  1. db.users.find().skip(3).limit(5);
    . C6 I9 V1 \( {& ?$ J
复制代码
! |* f3 O% a8 a& ?
查询记录条数count() 6 `+ ~% Z7 W9 Q8 S/ o  y  {
db.users.find().count(); 8 V* P9 T8 j1 J# C% n8 H  x
db.users.find({age:18}).count(); 7 {0 e& X8 Q& ~5 J: x! |+ Q
以下返回的不是5,而是user表中所有的记录数量 0 o$ M, A$ B3 H5 u$ _! F
db.users.find().skip(10).limit(5).count();
: ?1 Q) I, _% G; m, f  t+ [! J如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 6 h% _& O6 Q- c
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
8 W+ x  ~9 C# S+ u, p, R) T
" A! G  @2 P4 a) W7 E, }4 y/ F; \
分组group() 5 u' w- ^5 G- X+ C0 ^) I
假设test表只有以下一条数据
- a0 C4 P4 K% O* T: R
  1. { domain: "www.mongodb.org" , }. ]% F; {& F- t
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    ! x2 X- `2 w4 @2 s7 @$ _4 p  T
  3. , response_time: 0.05 8 x: [% r" I. g) A- R
  4. , http_action: "GET /display/DOCS/Aggregation" ; s2 H. v  s1 Q! d& S. \+ k
  5. }
复制代码
& M- u+ k* m  ?" `3 L3 z% b. |& [
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
- s3 I8 c. h8 l$ j: g
  1. db.test.group(
      J' p; v0 P) g* Y. f: t! ~
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} . L/ q! W4 z# A( C: m4 i$ I' F
  3. , key: {http_action: true}
    : l% w. I0 G8 P5 y+ S1 b
  4. , initial: {count: 0, total_time:0} / h4 J2 J: H" k
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 5 [6 ]9 w2 _+ D
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } ( @3 ]9 z: l3 [5 p
  7. } );
    2 X& S/ U( S, G& Y* `

  8. 4 v: B, @7 l* R# s/ h5 @$ _
  9. [
    6 ~& Y2 h1 T( ]+ m
  10. { ' J' @; S) s0 I3 _0 ~7 z8 ]- [
  11. "http_action" : "GET /display/DOCS/Aggregation", : ~. g' q$ s; }% b+ Q! {, C
  12. "count" : 1, ' s/ |8 p& ?. ]; g
  13. "total_time" : 0.05,
    9 t2 x5 [: M1 w- ~2 ^* J' A
  14. "avg_time" : 0.05 ) A' V. W$ F* J$ [  ]
  15. }
    0 ]" k" R7 u, ^; z
  16. ]
复制代码

' _3 l) U: X1 m2 ~
* w* c) @% {% q
# I0 u! z/ l1 M7 ^+ t, p) }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
    / \& I8 `8 D4 ]/ s! t
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
# t! [+ A' Z* Y6 u4 \2 z% z

: u6 t. C4 K' }- g6 C7 ~/ b, Q
5 m, E& r" j* F, k( \
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct
    ( N/ h- y3 h, H0 N# U1 ?
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
# _. P2 t* D3 j  F, F

: H+ U: e2 l6 e
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

1 |: E4 o  T3 @& o, t1 ~) Z$ a0 b. _. T
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
8 W& N7 s3 Z; V0 V+ H$ \1 E" i
4 Q: ]2 h1 C# `  r' ]
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
! g' y# J+ H" K  t0 w3 h

3 c" `% t( L$ s  }' l
输出如:
  1.         5 r$ M7 f' z% r" ]( L2 Y/ l
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
; a- c4 n+ l' p4 F

) r) V% b" q' _* W9 o5 R8 {* |3 Y4 @5 B1 }. a( M
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"/ T1 ?/ }+ i) q! v  g5 Z
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    ( b- t9 H/ Y2 B
  3.        xmlns:context="http://www.springframework.org/schema/context"
    6 X4 `8 ^8 W( \3 R0 i- f: b
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"/ O7 o# b! y0 v! q6 q' x1 S5 f
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans' U- ?+ i" d. _+ @4 P. n
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd1 O$ j' {; I6 t* J; V
  7.           http://www.springframework.org/schema/context
    : \* n; S9 v# a* @, N( Z
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd$ k1 b! s' p: w! M; l, V
  9.           http://www.springframework.org/schema/data/mongo
    4 j: }, z7 I( |
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"># s7 K2 l' m/ I* }, N% S

  11. - @3 P; s0 l" U& E; p! n
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    ) ~1 T! m; S2 H* v2 O

  13. 4 ]& f( q# q( ?* ]
  14.     <!-- Default bean name is 'mongo' -->
    . q8 Q, S, `* x* u4 C  b1 c8 j' J
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />0 r' R" D5 m8 {+ V1 E
  16. , D5 ?& D1 R" e; {7 b
  17.     <mongo:db-factory id="mongoDbFactory"' ?0 H% u) z6 W& A+ e+ @! n6 u
  18.                   mongo-ref="mongo"; \# X2 C1 }) g1 ~0 t; e
  19.                   dbname="mongotest" />  K; R+ d$ j( Y

  20. 1 Q1 I! k+ E1 X; {0 Y: S% b  ^
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"># w" |2 n2 f# h% o! ?1 C
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    1 K' c6 `  U, a+ B. x2 v
  23.     </bean>& {+ h8 f& g8 S3 F# O, P2 d$ l: W
  24. </beans>
复制代码
9 s" L" w' O. ^7 r6 s4 f: A

* a6 z- Z4 c0 D( h# p0 s7 [" W; I& A
maxmin的测试
  1. @Test8 f& _) T' U7 B/ @7 s7 W, ]
  2.     public void testMaxAndMinAge() throws Exception {
    2 h+ \) a( }, _
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    ( }. S9 ?/ ^0 l  t6 t+ h& d
  4.         Person result = mongoTemplate.findOne(q, Person.class);# o* _+ h7 l9 s8 R
  5.         log.info(result);
    1 l( r- R. k8 i! w6 z3 l
  6. 8 i; T0 N' X! m7 U4 p: n; A
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);" F2 o8 |, G3 y4 b
  8.         result = mongoTemplate.findOne(q, Person.class);
    ; l6 c$ J% \" E( a9 o) A9 Y4 _
  9.         log.info(result);
    : C" m2 ]! [" L8 V' x
  10.     }
复制代码
1 U, e! L& G8 z. N# {

6 R- [7 [. V" z% Q  X9 N
distinct的测试:
  1. @Test
    & I! z* u0 ?) {7 V2 ]# Z
  2.     public void testDistinct() throws Exception {  [% X, q* D2 R  @
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    # D6 M, ?8 i; Q5 C; Z* T, r2 Q
  4.         for (Object o : result) {
    . T, c0 v+ y5 b* ~& H7 h3 L
  5.             log.info(o);. H7 J0 q: j7 i1 B4 r3 ~  w
  6.         }
    " _1 I! U5 Y: P6 `8 `, a& Y4 Q* J( K$ r
  7. 8 h5 o" `8 a( ]  z! Z& H
  8.         log.info("==================================================================");9 V0 H( y& d/ I. M+ t0 d
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));2 \. {9 ^  r3 [6 ~% T
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());! v: Z5 \' q( o/ E1 U/ {
  11.         for (Object o : result) {
    * U  T: y* L  R
  12.             log.info(o);5 c: ]8 Y( c; f, z3 l* ?$ ?  ]9 j
  13.         }$ R% B$ K- t* Q2 h- u3 q( E

  14. 1 p! y2 A" r$ _; v
  15.         log.info("==================================================================");
    - ]6 }  _+ x' F* n, D1 ~
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    ) {+ g6 a& t7 I7 A( p- F  Y4 j
  17.         for (Object o : result) {: T$ S0 M) `5 T
  18.             log.info(o);
    7 e) [2 K* g, E  ^4 f
  19.         }8 M0 H8 J1 \0 X. o4 B2 R: v
  20.     }
复制代码

+ a) K" c) T* ~3 \; e
( J' S+ }3 k0 @  G4 W# W
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    0 Y' V  X) H4 a! o$ B# C
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    1 V& g6 u  I( g  |
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    & T' O/ v: A6 n6 n6 V
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
    : e3 j& K1 X5 }& X: s) u* Y8 \
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    2 d# e! V( I8 ~% a% ~* V# g
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    " x! t( t7 _$ v& w
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456& D' Y% d4 l2 x6 q1 t+ w
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================3 R: u- P: ^2 q
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567! h: v4 k. ^/ B% b5 C
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 3456780 A/ ~1 b4 u% o2 U5 y
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 4567893 k* b: Y7 P8 Z  z6 }* z
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    ' ^+ g7 [, @& Y: z6 {
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    . Y% |1 v* O' J
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa' O8 I" q  y7 s) s. Z
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    4 V. S4 K% P7 m
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc3 Y, B, _/ i$ |$ v0 T0 f' a
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www! T) v2 G. U: {+ k  `- S
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    . I  |: d8 M' k- A3 f8 r! t* W4 h7 z
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    % y+ H4 m7 d8 m9 E1 K; v% F! q
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    " b9 R: \9 J9 M- \
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    9 R3 O( j0 p1 W# V- 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
复制代码

- M- E5 h- k6 t* R+ ^6 \) ?
- Q) k, g# t( h
这里我要特别说明一下, 当使用了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等信息。
) q+ }, ?* ~+ M: Q

) [$ i$ P2 i( c/ b  x
1 q0 D5 \5 [/ Q, s
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-4-30 20:50 , Processed in 0.102800 second(s), 23 queries .

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