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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:3 `/ d& R7 ^- V' u$ {/ @, j- D
: V  Q( u6 c: J
1 ) . 大于,小于,大于或等于,小于或等于: x- D7 p$ h5 g" P) ?5 x0 w/ p8 O

1 a" V) Y+ i1 Y$gt:大于2 M, V  c% \1 w- e, H3 k, f
$lt:小于
. D* F6 R- D. G. ^. q' a$gte:大于或等于
1 D; c& n$ ?) J& o: [, a7 r" l$lte:小于或等于
! I9 g6 S: O; p; P5 R' }: z- {1 \( M8 M! X7 Q
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value2 O6 t+ H5 Y4 ~0 E
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value- I# u4 i8 e3 o' g
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value& o4 E# _* L1 _# p: R# g
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
( ]. b1 w1 Q. h
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    8 i; Y# O: [- G# R1 S+ M
  2. db.things.find({j : {$gte: 4}});
复制代码
1 P7 o1 o8 j9 {# n$ F) m& I) B
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
4 C  G( V+ X) k3 t4 j9 K. z" g
6 r2 @: x# _4 I- h; g' M

8 M/ \& n' A; N8 l" A/ S7 [5 p1 s
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
9 Z* e6 H; Z# k2 ]# j, {  @( S+ P
3) in 和 not in ($in $nin)
4 z8 M" G4 _- k% k& @/ I0 ~6 C, `
; k' n+ P$ e3 D& t3 H; H5 [/ j语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
0 S/ c: f  p' m6 V, `: V
例子:
  1. db.things.find({j:{$in: [2,4,6]}});6 W9 e2 y' Y2 i. O' `# w: e# r
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

1 m! S. D; T/ z. o8 m( H, d3 l
5 J! p% t& V% a$ s# Q' M" r9 b
4) 取模运算$mod
6 O8 V9 s. k1 K' u7 p  B1 r# L6 _! u. U5 g1 `* Q
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
2 t1 ^! j: k3 d" F8 d
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

3 e- ^( o6 f6 O" D- s0 {5 a

2 ]8 f& [  ?1 o6 L; h' T' p4 f5)  $all
& b, u3 |3 r3 N7 R& M+ ?# X1 \; Q
$ u0 i: g6 P- Y0 P! H( K; R* d$all和$in类似,但是他需要匹配条件内所有的值:" s* \5 h  J/ f# f* {; ~
, w6 T" C) Y: D( P6 s- \9 ^# W
如有一个对象:5 Y# k( ~9 x4 [
  1. { a: [ 1, 2, 3 ] }
复制代码
$ e" P9 F6 L  ?$ A# C
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
% v2 Q5 ?2 z5 I5 u& {/ U
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
; _0 B+ a  X$ x- J
4 c+ P, N8 l  `6 b# g9 F: R6 v
6)  $size* j3 a3 s4 P6 j" r

9 s0 u" w+ @# L3 j4 Y$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:1 M& W: u$ {# j& q
& z; P  g4 T( B1 L2 H4 g4 s
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

1 q. E- w0 o# i' D$ M. H
官网上说不能用来匹配一个范围内的元素,如果想找$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.
! f4 E3 F( _* L" B3 \; V
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回0 I8 e2 j$ e# m5 c9 j
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
* p: t( _7 e, t) H! j
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string( T  F+ ~$ `* y" @+ C5 @  E
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
8 y  J0 a% W5 T3 j% X4 o
9)正则表达式
2 F" Q, w: j8 x! ^, }7 k: ]9 ^3 K
9 d+ K( P4 h$ h( `# i$ Wmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

! B# ~1 T# l9 h$ k2 C9 L- r) o5 i
10)  查询数据内的值4 |' ~  o! }( K  i- r1 K$ N

5 }9 p& C9 a8 }( I下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

" {( ~4 ]3 E6 `; s* U) R
11) $elemMatch
1 A4 U5 P, ^( N. @  P. b# V" T0 Z
, ?: C* w6 Z. Z/ S) ?如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    % I7 U1 y! d9 w. Y, C: g6 |( D& f+ e% W
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
      U. A8 \2 w% M# G+ E7 [
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    % B9 v* K3 h0 Z7 \" a* x2 |6 r
  4. }
复制代码
# @* w4 F0 p( g2 J8 `
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
6 ^* n4 Y$ |& ]+ A# J
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } . e% l6 [# Y! q5 l& \$ F! g

% D1 l  m( a" @& \( t6 E12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
! K7 h& o  ^: W! k; k2 J) K. T* S4 K
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

9 L: g* G6 M0 q: G3 Z9 Y: N; R
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
" e! r4 ]% G) L* p; M3 s; Q+ w
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
7 O  k5 D) p% _7 k) g4 W
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

# R; Z- k3 ^' q1 }
是不能匹配的,因为mongodb对于子对象,他是精确匹配。

* ?! N0 @& h0 u* v5 X
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );$ M) k9 E9 S/ B
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
- N% e+ T) G1 f0 `
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
' j$ z! w7 g" E8 r; q$ d9 r4 b/ n
  E# c. J2 q* F$ v5 Y2 w6 mmongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
6 e( g" b+ }( s8 ?2 N
8 U) ]- M) E; S+ H( }( ~+ mhttp://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
# u! d/ A: D& d! Q7 P5 N5 v: K1 _& R$ N* i$ [: B
版本二:
8 [  i' |$ L, T# U/ r# Z8 ?7 E+ W6 C% Z
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
1 m1 Q: }1 W' z2 q- Q2 t
  1. use admin
复制代码

7 d' ]4 V6 M6 g9 Q; L
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
7 \& N& D8 i0 S5 S: G' ]
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

+ C# K  \4 U' f! b9 I/ `/ E
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

, [1 ^  K7 x$ G( E) ^/ r% J1 k
         5. #删除用户
  1.           db.removeUser('name')
复制代码
. V$ f% y8 E: S3 @
         6. #查看所有用户
  1.           show users
复制代码
& O' E9 r: \1 H) y
         7. #查看所有数据库
  1.           show dbs
复制代码

" \; \) a9 {  i4 X
         8. #查看所有的collection
  1.           show collections
复制代码
; a) ~. K, M) R# |8 f8 ]; |6 o' ^  }
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

" X7 p$ y) H1 t% }" V( L! k3 [
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

: w2 K5 N% x& G0 _
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
( z% O* I* `+ p2 h! Y- t0 F
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
& P5 _# e# P1 U3 S" x* P" V1 {
        13. #查看profiling
  1.           show profile
复制代码
( b$ f8 `2 i7 e1 }& F
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

, d' X! b% Z+ t+ J1 q$ y
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
! R. g$ g% C. d/ P+ d& y
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

9 D- ]4 b+ g, e/ T6 L2 n2 H
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
8 r3 q- C2 |; _8 i/ M
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
4 R$ [& U7 B" s( U8 j. @) T# I& R
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

! u; `5 ]' B( `5 m& i* O
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

. K! \; b7 x% Q3 Y
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

1 I2 o$ E+ X, q- N2 t9 b
   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 j3 o2 w& o+ g1 c& K( g3 X( M/ B8 V; ?
6.  高级查询
条件操作符 , w. W' O8 M8 R2 j; L, \
  1. $gt : >
    % h! r, K# S0 A: u3 Y# i7 c
  2. $lt : < ; V7 j! z! x% W* S
  3. $gte: >=
    - B) u9 R2 }& K" w2 Q$ J8 r
  4. $lte: <=
    2 p) T) x6 F' y% y2 S$ n
  5. $ne : !=、<>
    5 ?  G/ |/ B8 Z& q$ j. J
  6. $in : in
    ; e2 D4 @9 M4 g/ }1 K
  7. $nin: not in
    ; F. T) v( }  V' m' J7 K! I
  8. $all: all
    ; k1 u9 \$ {- W3 Z
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

1 ^" v) }+ S, N) @% c+ Q. g: K1 D% C# ?2 `$ q8 P2 O' z
查询 name <> "bruce" and age >= 18 的数据
2 K. g( G; p! |+ F  A
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
7 O7 j: t, s' S  o7 u9 C9 j* V
/ N. k, U% F+ h, P# C/ z7 z- T. O7 Y
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 ! s, Y, T  p( j& t4 W( o$ G1 V3 H
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
( p/ d1 l- m0 S2 A$ f; m- m
/ L! a- V$ q0 Z
查询 age in (20,22,24,26) 的数据
! _3 g: h/ O. E$ v
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码
+ j8 [4 y6 P+ d3 {3 U. P7 o

) E0 k. B  Y) b# ]: {查询 age取模10等于0 的数据
1 E% k9 \" S* y5 E
  1. db.users.find('this.age % 10 == 0');
复制代码
$ s$ g4 M" c! ^6 @- K. j/ h6 o. h
或者
2 k4 o# Q9 M0 y) a& }' V
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

3 |0 l9 q. M% g- M3 t' [2 T+ U' ^4 _* V  |$ i( l# V
匹配所有
6 l$ w) j+ h3 q( J8 {& [
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
) J" ~, `6 q9 s6 j/ S
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 7 P& j( @- K2 _* {
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } / c# S- }/ i1 M
$ W0 ^( R3 N6 e+ w( @
查询不匹配name=B*带头的记录
( x9 Y4 d8 W9 P" }. j
  1. db.users.find({name: {$not: /^B.*/}});
复制代码
0 v" g2 T! y! P1 g
查询 age取模10不等于0 的数据 2 J" v* Z$ C: g0 f  |: t
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
2 P4 b0 X: N: _1 Y; }

% l" Y" p4 |  F: C% d#返回部分字段
+ ?" h! Z6 [7 I, {. _选择返回age和_id字段(_id字段总是会被返回)
9 s9 s5 ]. z( ]
  1. db.users.find({}, {age:1}); ( i8 I( J5 o8 r" M
  2. db.users.find({}, {age:3}); " L; C0 r( p% u7 V$ N4 {/ W" k
  3. db.users.find({}, {age:true});
    + f6 q4 \! _/ ]; c4 n" R4 U
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
4 a, C' G- d; v
0为false, 非0为true / A7 @, [' w, z6 @

2 x- t! R8 t5 l. u" Q, |4 e6 }选择返回age、address和_id字段 / S3 c. e: r5 X# `+ j* Z  d
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
; i8 m7 H& r$ J1 q! [3 b
1 F( S8 t! D# W# c( E, V
排除返回age、address和_id字段
$ d" h* {9 K! T& r0 K
  1. db.users.find({}, {age:0, address:false}); 3 \% Z: b  U0 d% p/ r- F
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
0 N3 N, Y7 x, J0 @

. J" J8 R2 I' d! W" L% L数组元素个数判断
& C9 W) k2 \2 k9 s2 T. \对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
, z) o& i* J7 l0 i匹配db.users.find({favorite_number: {$size: 3}}); / i0 N* r* v' X0 R  z7 Z
不匹配db.users.find({favorite_number: {$size: 2}});
) _  |. V' [% f: K/ D1 d6 n
& u+ q  y# S' P( C7 O8 G/ o! W$exists判断字段是否存在
! S+ K7 r9 D) O3 e: v( |查询所有存在name字段的记录 # v% ^7 U) W6 I8 \1 E
  1. db.users.find({name: {$exists: true}});
复制代码

1 X" c4 X8 q; |查询所有不存在phone字段的记录 ' {+ s0 I/ q+ T+ R( r: ^
  1. db.users.find({phone: {$exists: false}});
复制代码
0 [: J4 O' V: A+ ?9 F7 \. Y, s

4 j: K2 ~$ z/ t4 o6 {$type判断字段类型
7 X! x1 ?' x: ~2 z! q( a查询所有name字段是字符类型的
8 }$ t% @+ z) C; ^, v
  1. db.users.find({name: {$type: 2}});
    5 T4 M) R9 b% p7 b0 L
复制代码

$ ]3 u9 l2 @3 t$ ^查询所有age字段是整型的 4 J) \0 L! E6 f8 ?3 L1 T$ C+ T, P
  1. db.users.find({age: {$type: 16}}); & [: {; h) m3 _, ~
复制代码

; }7 |# g1 o  d, {对于字符字段,可以使用正则表达式
( U4 V! z: P0 b3 ?2 |查询以字母b或者B带头的所有记录 , O4 N' f0 L4 s* j! U  C( h& I
  1. db.users.find({name: /^b.*/i}); ) E+ O/ n6 R0 ?% q% Q
复制代码

$ w6 T) V* w' L4 g$elemMatch(1.3.1及以上版本) , E* b* g7 J1 A* k6 O& X, R
为数组的字段中匹配其中某个元素
7 h1 M- `* N2 q, X& h7 E' D0 \+ s) j  t
Javascript查询和$where查询 + c5 F$ h) e* }9 g3 O
查询 age > 18 的记录,以下查询都一样 & [! V' B8 L1 z- c7 c
  1. db.users.find({age: {$gt: 18}}); - S5 w' i( t8 y
  2. db.users.find({$where: "this.age > 18"});
    1 v- A' ~/ ]0 L* @# {
  3. db.users.find("this.age > 18");
    , X) F4 S; P. [! _
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

) U% c6 x0 O; ]$ S+ }; v3 x3 U* h+ Y, Y& E/ ]. t3 I( E$ X
排序sort() $ l* i  k3 s" A
以年龄升序asc 0 Q3 E6 ]* G; U' V) U, G
  1. db.users.find().sort({age: 1}); 9 e) L  z8 @0 l9 u5 s7 f' I1 q
复制代码

4 Z/ |) H2 |: ]' G, ~; U# Y: g以年龄降序desc * s6 m* l2 M9 a( Y' w; q5 @" h
  1. db.users.find().sort({age: -1});
    7 Q( c- D" _7 Q+ b8 |0 T* n
复制代码
3 d; b- e$ ^. @1 [
限制返回记录数量limit() ) @5 Q+ v3 r; o; |3 t4 ^' \
返回5条记录
* E" h6 w6 \* Z
  1. db.users.find().limit(5); 0 V1 ?1 E7 @! c; J6 n9 s( G) g& O
复制代码
1 ~" {* u, C& }
返回3条记录并打印信息 # S8 a& P  m9 O! W" `
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    / x1 J' v6 Y; y% J
复制代码
) d2 n: Q1 [  d; F* R# S9 Z5 O2 F
结果 : W& I+ _- h1 B: i, I. f
  1. my age is 18 1 m. e, g  Y: V0 D+ h
  2. my age is 19 ; i( h. b* Z1 U) d+ p; v) v; d* i
  3. my age is 20
复制代码

, N" b8 F( a9 J' S6 x
; V4 f: k) _0 }+ [. @7 z限制返回记录的开始点skip()   k! _8 j" [4 E% t& @
从第3条记录开始,返回5条记录(limit 3, 5) : w* g+ q* Z, {# i) t; }! |
  1. db.users.find().skip(3).limit(5); ! l4 \" D# n; Y# V" \& x+ d
复制代码

8 k( L8 B% t, X( V查询记录条数count() ; L, e7 r( ~, N; R7 w
db.users.find().count();
, T0 _2 G" L+ T! I* X1 `db.users.find({age:18}).count();
# L2 p8 T: V* E3 B* H2 L6 B以下返回的不是5,而是user表中所有的记录数量
$ [+ R3 O% E, f9 _3 z( Z5 idb.users.find().skip(10).limit(5).count(); 7 A9 R# R: x9 z( z. Z" Q. [
如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 1 T* w" u# }3 l% f7 p8 L
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

& F) o. ^) I& M: t3 r( y" v( K+ S8 n* U
分组group()
1 k3 z' y" v- T+ Y: v假设test表只有以下一条数据 4 ?* v4 S. B8 \7 F; m
  1. { domain: "www.mongodb.org" - ~- P# F) L# R3 O5 e* W4 t
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} 4 r# x& h, E% |/ J' {& U
  3. , response_time: 0.05 " c8 p  Y; M6 G) }) D/ C
  4. , http_action: "GET /display/DOCS/Aggregation" 7 a4 z7 n0 r* U0 w3 \
  5. }
复制代码

  G! U- j  {& j+ _% R使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; . d1 s% J2 `. P4 q6 r3 n
  1. db.test.group( ) S5 A  l2 q9 d+ l
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} " }+ {6 q1 X% ]+ G! \- z
  3. , key: {http_action: true}
    7 r* _1 `& F0 y, K4 e! O% D
  4. , initial: {count: 0, total_time:0} # [% s6 H4 }: T5 W
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    $ L) j  h) c. p4 T$ C9 e* ^
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    1 m' R  m' ~8 P" F
  7. } ); 9 _! e; ?$ O1 T- L2 f) B0 \, h! E

  8. 4 f2 {1 x! Z4 ~/ r% C0 P. x1 M# I
  9. [ % a" p9 N- O2 e3 x; I
  10. { 7 }0 X' p3 Z3 H& T$ ~7 H
  11. "http_action" : "GET /display/DOCS/Aggregation",
    & C7 i  y# d' P! C2 F
  12. "count" : 1,
    4 q7 y1 m, N+ g$ T- o
  13. "total_time" : 0.05, + n# Z) y* J; X3 r7 F( ?. j4 T7 {
  14. "avg_time" : 0.05 8 m% e% b. X4 u- w& u
  15. } + g2 d6 z/ f% h6 o$ D  b. P
  16. ]
复制代码
8 u: w4 L* N8 ^; a) m: w) S
# [7 ~! G' A7 ?$ K! p
" M# x& d" a# `* ]4 q0 ?5 n
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
    ) ~8 r7 w8 v2 u; Z1 J
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

; ~) R1 B6 r6 e7 W9 u$ A" e# M  O8 v- b5 k# i

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

$ H( @0 p8 d. V" {
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
# a/ O4 E+ [1 X3 N3 K
) t! ]% I( r" {1 n/ e+ A1 K
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
1 M: a2 p4 w  Q4 r* `
  z, L: ?6 ^3 z( a5 ]( k
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

" Z7 z: D# R; ?; ~/ ]9 t
( z' C7 m: e4 _" F9 Q+ g
输出如:
  1.         
    5 l5 V7 d& l# k5 X1 ?6 }; D% ~9 B
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
: C" }; r! u  [' z' P& \
; a2 u6 J5 [" {5 I& H- z/ m
* r; @1 m6 o+ X9 w9 [; B* {
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"* K8 d/ U2 R: w0 y$ P6 t2 ~" i
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    * u1 L: i# O& i* D0 P8 f- c
  3.        xmlns:context="http://www.springframework.org/schema/context"# T5 i% P- W# P  t" f, U! L0 ^
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo": W; ~4 E$ l; B& }4 S: n9 a' ]; J
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    ' D! S! k9 W/ H6 ^; G
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    ! V: Y2 Y: Z8 t# ?  ?
  7.           http://www.springframework.org/schema/context1 M$ n  {2 p+ S
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    8 Q! Z! y, w$ h( |
  9.           http://www.springframework.org/schema/data/mongo
    , T& Z; u  m! t3 _, G# y$ p
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">" N0 U+ m5 t8 n" U" n- t' x6 f5 y. J+ {
  11. 8 x! c. h) B: y* }' u4 Y+ k
  12.     <context:property-placeholder location="classpath:mongo.properties" />1 D' I. e6 L3 A
  13.   H# z% P& l. Y7 m: L3 w0 h
  14.     <!-- Default bean name is 'mongo' -->1 T" w9 R4 _: v
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />8 c- ~8 |# o( ?" c9 S0 I% a( R. x" t

  16. / ]2 d- R3 H0 k5 T- E
  17.     <mongo:db-factory id="mongoDbFactory"
    ) b2 Q2 [' {! x; J+ A2 P
  18.                   mongo-ref="mongo"5 F7 @( T) y+ [) J% ]# p
  19.                   dbname="mongotest" />
    * T# k2 t0 j( r9 f8 V. |

  20. ! f) a6 N1 o3 t4 m
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    ' c: l+ M; U+ ^; I8 l
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>9 U" |" Z# a0 y! W/ C# n/ e
  23.     </bean>! ^, k% c2 \0 n" J
  24. </beans>
复制代码
- n; x' u/ X7 q* h4 M4 t6 K9 N' E

3 ?5 k. y$ I# ?1 K
maxmin的测试
  1. @Test% g- o* T0 F( D/ v7 X
  2.     public void testMaxAndMinAge() throws Exception {. y% q+ z" m( I  o; T! s
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);4 ~* q  ]# D0 V" @# x
  4.         Person result = mongoTemplate.findOne(q, Person.class);% f; u) i6 Y- j% G
  5.         log.info(result);4 w. G& O" W# ?% A
  6. 1 t0 H( F7 s& W
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);& F9 Q" B+ j- F/ g$ d: Y9 g8 s' a
  8.         result = mongoTemplate.findOne(q, Person.class);& s( M8 {9 B* r  j1 M- o5 O
  9.         log.info(result);
    ( r, k( }: p) J' w; M2 D& p( v1 U
  10.     }
复制代码

7 H6 t! Z. f8 A0 D* L7 A# c. Y1 D9 b
distinct的测试:
  1. @Test6 A! p! m1 t. _
  2.     public void testDistinct() throws Exception {  U4 @8 N6 K+ ~- i) _0 X4 C
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");1 q# @8 z8 j5 U1 y
  4.         for (Object o : result) {
    1 @( S9 ]8 L- [( a: j% F
  5.             log.info(o);
    , X  F# P$ P' i
  6.         }% Q; s& E% h$ R# [/ a# ~1 ]# j/ v
  7. * F( U+ U! j# S
  8.         log.info("==================================================================");
    0 ^/ w: x$ k# \
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    . D) E; R( l/ [4 V# J
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());0 y' p  @* M/ s4 n0 T! x3 W
  11.         for (Object o : result) {
    . {6 x- Z% Y. D
  12.             log.info(o);
    / [2 o# ?& e$ k7 S8 b& b: |6 |% Q# v
  13.         }, Z- h6 B& x* f6 K8 T

  14. - L7 f* p6 x/ R( S# x, `
  15.         log.info("==================================================================");% b) e4 V+ Q& `/ }8 U. p; D+ M/ w
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");2 @5 K- W( p6 o2 e3 b
  17.         for (Object o : result) {8 M' V, U3 ^0 C: T# y8 q
  18.             log.info(o);
    ' U# X8 N) a, a6 _5 P6 Y
  19.         }
    ) C$ m9 [7 L5 P) |7 ^$ X  m! w
  20.     }
复制代码

6 s) E0 V8 A1 e! a5 R- A# v; R1 \' a, m2 R9 F
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567" k7 v* Z, @5 ?0 X* }) M. n8 b
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    ' C$ \$ i0 V6 F
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    7 B; Q; C& V3 x+ V1 J: y' K
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
    8 R  |. D1 E3 D9 C7 ]
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    & f* E' |  l4 t* K
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo2 V* ~0 d3 E! R/ G3 G  q+ }  ^
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 1234560 t% s9 p' j7 t- n) m  u
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================( `2 x) A/ `5 ]
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
      S; r9 ?( X+ F; I' Q
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    ; ?2 s- Y7 z1 |. o4 ^/ ^
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    0 {3 m% u2 I: g6 O5 \1 z7 x2 {
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876548 M+ H5 n$ ~# B- M& V
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    7 B6 h8 Q- h1 I
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa- M. Q( H+ h: J/ V( j( q( ?
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb0 F& a) T. s, A/ `
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc, P. Q1 @2 i- T; H0 r
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    1 Y. P/ ~1 t$ [( B- f
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx6 U" S: W: I& |5 {! r4 Y# n& f9 C
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy( @! V3 t6 a( A* t+ Z
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    * s8 i+ {4 {9 J# r+ R
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr" y( h2 ?- R$ F- m4 J
  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
复制代码
6 ^" `  C8 {3 n( E. \& G9 o

2 \+ _1 t0 N# U7 K
这里我要特别说明一下, 当使用了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等信息。

$ j; C: v6 M. o& g
0 q/ k: \  y, r; H! E, ?
  q1 w: h: H* J  u7 U1 n
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-1-30 16:45 , Processed in 0.070189 second(s), 23 queries .

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