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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

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

, [" Y+ E' H9 c# u* h4 f9 g' d+ g1 ) . 大于,小于,大于或等于,小于或等于
& Q+ n9 j' b" d5 ?1 z9 |7 T6 p& e. I% r
$gt:大于. N4 C2 Q+ m* _
$lt:小于7 s5 h1 e$ J0 ]' ]- r
$gte:大于或等于* F- r. m( j& j* v1 h: J
$lte:小于或等于. T, h5 A- G0 T  d; n! J: @$ T7 O

9 L* I- k( t' R8 \0 G. M4 x例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value! o7 q6 t4 Z) ]) x
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    + y1 l$ |6 B9 F7 p! q3 B8 J, s- x' e
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value  \9 a* W  n( f0 I7 B9 M
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

) f8 T; J  b* `
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    & ]/ F2 f  A" N% l# D
  2. db.things.find({j : {$gte: 4}});
复制代码

5 s1 R1 c5 F1 \! z, D& U, A9 o
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

! f! P# @% s. @" m* v- n2 ?! k+ n
- \9 H: T% C: G5 O6 a' f9 c
" h2 L) L/ l: ~3 c: ^- [+ |1 f
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

/ S, ~5 B% ]' h. q1 ~% \2 a
3) in 和 not in ($in $nin)7 t& P2 j5 `/ t$ i7 I' C6 s6 N

% x, ?, |2 N; T, P) J! b语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

/ x, A& ~% x' h) @( b9 w
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    & N+ l$ f( m9 L4 W
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
% T( a. Z7 ~- N+ s- \% P' b

7 L0 k- ?6 M( C. J7 w4) 取模运算$mod
( {0 s2 U! w& e
+ F. [$ w9 {: R, ^: G2 q3 U如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
% w7 @: k$ _+ ^3 _1 g( t
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

' Z* C4 ~1 R) P, N; a

5 K6 s* }7 q( {3 I) j* [5)  $all6 a, F+ Z, @( @- M  {- E

1 e4 J7 _- f* s/ h6 l( c' |$ u% m$all和$in类似,但是他需要匹配条件内所有的值:' A. O* ^2 }0 T+ b; J. \! m0 B; p
7 f4 d( {, `$ ~3 @
如有一个对象:$ k# ^+ q- H2 a. h
  1. { a: [ 1, 2, 3 ] }
复制代码

- x4 o6 a& F# x3 ?
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
& r4 k& R1 b& n# @6 t) p9 q
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

6 Z' a' L1 S; K; T

# S; j4 f4 R! k$ S0 u5 B/ h6 G2 m6)  $size# \) t- P, W: V  U7 Z1 Z
  y; i& j, N/ D0 y" ^) I
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
# C* z* V( k' @& Q" [2 R* O- c5 q4 j  W) g, J/ [9 Y1 P: L: ~
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

( i+ U  l3 ]  l8 k+ i; q
官网上说不能用来匹配一个范围内的元素,如果想找$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* e8 W, Y- U+ m+ ]- g' i
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    1 ?% G9 G/ \5 J: e2 P
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
9 x# m" T9 ^; R$ @5 e
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    ! }8 u' }, H6 a4 ^- T
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
" w, k' n0 n9 g% s3 q
9)正则表达式( V/ V7 }: [4 v5 ]
8 U& k3 z" B7 ?  o( K  ?
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

; q) Z3 {- i6 m, A0 u$ f
10)  查询数据内的值
( p  R" K/ S1 _% A
$ P! C5 o; A' I: M) ~$ l下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
% b. H& ~. z2 V! ]* ^7 d; O
11) $elemMatch" |0 h, |, K8 U1 y! G, O: n

+ u% }4 Q9 p" B% `5 M9 |4 B2 ^! a- t如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    5 V4 e7 |. ~8 [& z7 G+ G( ^
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    $ ^# |% r. N- m. W; v! W
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]  A* M* `0 ?3 P* B4 k
  4. }
复制代码

' c# A" _; s, `  E+ Y1 l$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )% F& U1 |+ a- ^) G* R1 m, H* b
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
# A1 @: U- ~/ |) c
. d# ]' n) u% e6 I! D/ b12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
5 t) i+ _: H3 R; D7 ]
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

$ z) F% _. H1 v( Y3 {) O0 X  D
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
0 z' S$ n! A9 D  u1 a, T
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
7 ~- _9 X- e9 b: C( L5 t5 R  ?9 G0 ]
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
9 r0 J! ]( v  Y
是不能匹配的,因为mongodb对于子对象,他是精确匹配。

- M6 C$ y6 U/ u# P
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );
    : D, }! }, |; e$ p/ I9 ]
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

' U7 W6 l, \2 m
mongodb还有很多函数可以用,如排序,统计等,请参考原文。9 ^. x0 B4 G0 i! o

# R5 a% x3 F! Q: C  a0 n/ V, [mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
$ \5 y3 n( w% N/ G7 `; g; Q2 m& y  y! |+ A+ l
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions) z  e* l' Y+ z2 E6 c# F

( t8 P. r, n. Y版本二:
+ m$ ^2 j+ d/ D( i' V+ d0 A' M, [0 U
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

7 Q% s0 T2 Q& f; Z
  1. use admin
复制代码
$ @0 e$ p  [6 @1 d4 F6 a
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码

7 v# K1 s2 @0 G' D
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
$ R/ k0 c0 ?, F2 U8 C
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

" j+ L1 y5 e/ A0 _, A3 d& t
         5. #删除用户
  1.           db.removeUser('name')
复制代码
+ T- E9 z% L% k
         6. #查看所有用户
  1.           show users
复制代码

5 y( I- Z' [$ V6 p0 _& N
         7. #查看所有数据库
  1.           show dbs
复制代码

: K' R3 x2 J2 c/ f6 v
         8. #查看所有的collection
  1.           show collections
复制代码

& R9 a2 J* A- @" O4 T& {/ f
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

4 Z' I4 s' d3 {5 P9 r
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
. X% O. A& f2 R3 M1 n
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

- I; p7 [2 w  k
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
# Z& q, l# V9 s0 N% j" V- ?
        13. #查看profiling
  1.           show profile
复制代码

& v) O% A6 k: W. z( P
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

4 B+ U+ D+ c6 |8 h
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
* F2 I' I5 m* E$ q
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

+ \8 o. [( S0 F5 h
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
1 z3 a) n5 N& b1 \6 y# p
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
6 p1 [. t; E( ?" [( t
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
7 o" r5 y3 v5 g# O0 Z  R( Q
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码
# X, n+ @* `. r3 _
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
& ^3 |" Y) L0 F7 S3 O5 ^
   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()

* w' ?3 I4 E8 Q% l( i
6.  高级查询
条件操作符
+ c0 t' \3 K! X
  1. $gt : > ! y$ t# c& e! B2 i: m
  2. $lt : <
    % S2 [: N  H( ]% f: F6 @
  3. $gte: >= / w2 s4 M* [: V2 y% @" g' e
  4. $lte: <= * Q7 T( T" }' F' ]( g* n
  5. $ne : !=、<> ' V! {% D$ }$ Z- F2 c0 V4 \5 _3 ^
  6. $in : in
    1 n% v# D3 b, A# w
  7. $nin: not in 6 ^5 S8 n% ^/ g+ D
  8. $all: all
    1 j9 E' f$ Q* A7 [
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
- P7 b, I5 d# g4 T; m2 E

* P; L- B' w' A- {8 C9 C9 |查询 name <> "bruce" and age >= 18 的数据
7 L  }4 E- f8 {# h. n8 E2 E, R
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
2 L: V  p, A( P; q8 d5 s

' J4 s% z& B/ ~! |* _查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
, r5 K: l: z0 t
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

, z8 d% N( m% C0 S# Q, ]
5 v8 C! o% p, [- c3 D查询 age in (20,22,24,26) 的数据
: [8 c/ v% |1 d* y
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

0 ]/ a6 c7 I+ M4 }6 I# F+ T
; g: D% x, f7 d查询 age取模10等于0 的数据 ! O: Y3 Z  O/ [" N8 Q0 S
  1. db.users.find('this.age % 10 == 0');
复制代码

- `3 c5 i4 _2 s, `7 Q( a4 e或者 - _; }+ |$ r1 |& \: B
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
% \2 m8 C  ?5 a* Z% r
! H9 n; m+ a9 V2 ~, R( W+ h2 t, f
匹配所有
1 j4 g9 U" d6 c2 {
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
  ^) K8 M4 W- u: n3 z5 n
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 3 d2 E. z# J  C( q( E" `  d% z
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } 9 U9 ]/ r# f1 r" V- \. j1 m
* T* l3 b, P# ~9 m; w% K; |2 |6 J
查询不匹配name=B*带头的记录
1 |$ P! |/ a0 ~- `
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

0 u8 H$ S6 B/ V7 \& {查询 age取模10不等于0 的数据 # e% B2 M4 N% k4 C
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

' A8 H* Z* l" }  n) I  Y
+ t' f* ]  ~6 g1 r$ W#返回部分字段 - c6 W$ g0 o/ e% E- E
选择返回age和_id字段(_id字段总是会被返回) ( C2 ?" r( l4 g- G
  1. db.users.find({}, {age:1}); $ c3 s; Z/ y; D* f
  2. db.users.find({}, {age:3}); 4 \6 p% d5 A3 C; p( W( t
  3. db.users.find({}, {age:true});
    9 s  p- t) z( d+ S' y& J
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
( F! X, B2 ^. j3 a
0为false, 非0为true
0 C- D4 r4 R" l5 Q( L$ n9 ~6 A
7 Y% G# X3 U+ i* {选择返回age、address和_id字段
; l& [/ N1 ~$ W/ q& q1 W  {5 \% T
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

" J( t/ ~! ]% t  ]# I) G0 y/ Y0 M% O+ o$ S0 \( A
排除返回age、address和_id字段
6 ~% N' o- P$ a4 D8 o, w% x: Q0 K
  1. db.users.find({}, {age:0, address:false});
    ; o* L5 y( f- {$ v7 S
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
3 Q# |/ r/ I0 x/ m* @

! A1 w% E! Z% e: b' U5 W数组元素个数判断 / c0 S( o( b; J  ~3 ?' g5 M
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 $ g8 ^$ z0 W9 O4 u/ \- s" f, k
匹配db.users.find({favorite_number: {$size: 3}});
- Y' S5 P+ w. g% v" q( x9 H不匹配db.users.find({favorite_number: {$size: 2}});
/ h6 F' Y% x1 l1 ?1 A( b% {+ L( Y$ F5 {# s% G9 {, {
$exists判断字段是否存在 : e  F  J% i6 r. L7 d% O' Z
查询所有存在name字段的记录
) z* i2 Z2 H  \6 [' ]  Y( _: d
  1. db.users.find({name: {$exists: true}});
复制代码

- O, D: A+ V6 n0 L+ M9 }" s$ \查询所有不存在phone字段的记录
3 D. F  I8 T# c% {
  1. db.users.find({phone: {$exists: false}});
复制代码

- |$ q7 H5 f# u( G' l3 e# s3 k  P
8 A) ?' k# E7 Q& c$ W- @$type判断字段类型
; g; l5 A2 L7 p  K; Q+ W0 {" s% J查询所有name字段是字符类型的 # U* o! l# c. `, ~7 q0 ^" W  q" v
  1. db.users.find({name: {$type: 2}}); 2 s" f5 d' v0 k  u' i6 V/ o
复制代码

2 d+ h: I1 Y2 o! p3 X( z) C, z1 D8 S查询所有age字段是整型的 7 z* A& U% @7 ~; A, [
  1. db.users.find({age: {$type: 16}}); * e9 u& h. U: y* J6 C5 W
复制代码

: H- a4 Q' q1 k: O对于字符字段,可以使用正则表达式
6 P3 z, q5 y. U8 S3 M' c查询以字母b或者B带头的所有记录 ; f) D( x; f6 R9 a0 ]- O5 q
  1. db.users.find({name: /^b.*/i}); . k8 X6 Z$ x) f4 `9 ~1 y" g( F+ G
复制代码

6 K1 D) Q6 q& Y$elemMatch(1.3.1及以上版本)
: A& Q4 R$ e  h1 _/ L* q! s为数组的字段中匹配其中某个元素 % D0 d7 z0 J. L0 c

) y% U8 R! E: p0 j( o( \# MJavascript查询和$where查询 9 j  u3 r  W: `' l, t2 \; O
查询 age > 18 的记录,以下查询都一样
" K+ a2 h- I7 s5 ^4 A% S/ a
  1. db.users.find({age: {$gt: 18}});
    ) M/ y: s$ E8 C! g2 H6 M
  2. db.users.find({$where: "this.age > 18"});
    $ H6 ^4 L( m; K. j
  3. db.users.find("this.age > 18");
    " ~% Y6 ^: u7 _
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
# N1 k2 g8 t- x5 h- Y& _9 t
0 l$ N6 V7 B- J+ A6 h0 z2 x
排序sort() ! x: U2 M0 Q) A/ _5 H: Y7 J: E
以年龄升序asc
, u; W0 Y; B) F4 d+ T4 n# Z
  1. db.users.find().sort({age: 1}); ' R# d0 c" J. r3 G& H+ B
复制代码

! a" K% t& ?( P, N% L; C$ f1 o以年龄降序desc ) ~  J7 T" A; V1 g0 Q
  1. db.users.find().sort({age: -1});
    2 a. D, _" i# l" a2 T8 Z  v
复制代码

- f8 v, W' B/ O" g$ c2 S限制返回记录数量limit() 4 L( F- R1 p. I9 J# E6 s/ j- ]
返回5条记录
9 B; E" u4 C. K' m, F4 i
  1. db.users.find().limit(5);
    + t  ]; c% j" g+ i3 p& H
复制代码

" J- X" {4 x) L% Y' k返回3条记录并打印信息 ( q8 V! P- X) O# p' a6 I
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); % B) T; y$ ^) N, p: }
复制代码

2 h% u: F/ }. t: z) G/ E$ Z! U& v结果
, X  i9 }2 \4 S& T/ Q6 `
  1. my age is 18 ! n, v, X% W, y7 a6 J% V% U% B
  2. my age is 19
    3 E* P: k% d- l0 @9 F2 X
  3. my age is 20
复制代码
6 e, u4 R& j6 [' @7 C" [* o1 e1 P6 C
3 I9 S3 @/ @8 d9 h- K
限制返回记录的开始点skip() 6 W, I' N. `% r: W2 K. {: T: p+ Y
从第3条记录开始,返回5条记录(limit 3, 5) 6 V( W& |, |. @+ {
  1. db.users.find().skip(3).limit(5);
    ! a' G& s" a$ ?! N$ ?( C
复制代码
; a; i1 o! p, E6 @  N+ p
查询记录条数count()
2 `9 g6 Y# w7 f# Cdb.users.find().count();
3 r- b7 p0 L' r; zdb.users.find({age:18}).count();
  A+ o# O6 c+ v: Q! k2 ^  i* C4 ~以下返回的不是5,而是user表中所有的记录数量
  e  Q- v" P" M6 k/ Q# Jdb.users.find().skip(10).limit(5).count();
! l8 M- j  A3 `如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
9 h- d1 l& K* t, L8 N5 E
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
3 y. o4 j+ W" w( B% L1 d
+ G9 ?( E3 A7 m% W. w
分组group()
0 `! s5 S% v) o" y9 e4 e假设test表只有以下一条数据 ( E* s/ U# k4 R  _0 P
  1. { domain: "www.mongodb.org"
    7 k0 s7 h( {- }' S. a( I& f
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    * b, C& j' O5 u; u, f- W* o0 l8 A
  3. , response_time: 0.05
    0 W7 h- s) D' b" o
  4. , http_action: "GET /display/DOCS/Aggregation" & l+ Y( g+ b4 x: ]
  5. }
复制代码
  }* Y( H7 z+ v8 P" s9 b! i
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
& q- b$ T( V$ a+ B0 h5 S5 \
  1. db.test.group( 4 |* v4 C. b+ b  h) R, O6 L
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} & w' \3 \0 v# S1 o
  3. , key: {http_action: true}
    $ o) y" B2 z/ n; G1 ~
  4. , initial: {count: 0, total_time:0}
    + }# S+ ?' ]; H7 M: ]! ]- j
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    7 T3 X; C. N7 b( G
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    ( s; \8 r& g+ j) P- X( u- t  q
  7. } ); 6 I' L5 o. s4 b
  8. 8 e$ N2 w! F) w+ S% ?0 n1 \
  9. [
    4 @6 k: \* c' e2 X, j
  10. {
    / H' {) ^6 y! r1 N5 `2 Q" i
  11. "http_action" : "GET /display/DOCS/Aggregation",
    4 ]' Q0 G* n9 G8 Z9 T- q
  12. "count" : 1, 6 s1 P0 y0 s% l5 P
  13. "total_time" : 0.05, 5 `8 s% X; a1 j4 g. {
  14. "avg_time" : 0.05 5 x* U. g0 d( p: m# ~. _. W5 F) B
  15. }
    * v8 [2 M- p8 Q/ o1 {
  16. ]
复制代码

3 `6 E1 q3 l1 ]- j* m
. p- U' s1 b5 k
  B$ {; Q2 w# H; f: MMongoDB 高级聚合查询
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* I; P" j8 O
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
- h9 Y" [1 i: ?; M, @4 _7 g7 v' |
5 X1 D( N2 K# w6 r, [

0 W. T9 J: ?4 q* }' s/ U
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct
      z+ s2 k! b# U( w: j" n  y
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
; L  l: [6 v- m- r
& g4 ~% G# U7 l5 [8 @
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
. J# q% \/ C- Q8 h8 M

3 _1 N# C% y' N+ ?5 y  i0 W7 Q9 C) f
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
& F7 x& A* x/ d

, y; [2 ?# {% c, k: }
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
. ^7 S) X; y% V3 k; M! G
: J! Y/ P/ X) R+ P3 }, W$ G
输出如:
  1.         
    8 z; Q% \7 C. @" k' x; T
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
; O; r2 p; o! Y# j# C
! t6 }  Z  D; w+ k/ R" Z3 r0 `2 D

4 {" `" F- _2 e  ]
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"
    . U4 N$ r" K7 _. z: X
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    ' r6 y) a  X6 i
  3.        xmlns:context="http://www.springframework.org/schema/context"
    9 J8 W1 l5 q3 b+ w* B
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"4 f' Q, U1 `7 K" I4 k, d, x
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    ; W) t5 G# U# R8 [% @( w
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    & m! Q" N% g; ?/ _9 q' H
  7.           http://www.springframework.org/schema/context
    , A! J( e" I. h6 h- E
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    ) B$ e. H9 O$ V3 s
  9.           http://www.springframework.org/schema/data/mongo! T5 M% q: |5 X* ]- O+ K; P6 d: l; Q/ k
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">3 \# L) Z0 n- I+ s' Q

  11. # ~4 g' \1 @9 G% H! @
  12.     <context:property-placeholder location="classpath:mongo.properties" />+ ?$ M- V& B* e& Z( d

  13. * g5 r. g0 {+ o+ l
  14.     <!-- Default bean name is 'mongo' -->. i7 k% m* Y6 `: Y8 q
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    ) {, @* \9 ~- U. A; K# v  @
  16. / C: w$ ^0 m& p& p7 z; C; u' a
  17.     <mongo:db-factory id="mongoDbFactory"  l; M" U: o- O5 J
  18.                   mongo-ref="mongo"
    ' |7 z0 V* T' i- d: R$ Y: X2 f
  19.                   dbname="mongotest" />% @' Z. G- S# _5 A) P; u
  20. " ~+ V! W( Y! C9 U6 n
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">! f) Z- R. I8 ]2 w) T* h" H# @
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>4 {& W" Z/ y6 H, Y3 c/ n
  23.     </bean>% _: c0 w/ B& W& R! a/ B
  24. </beans>
复制代码

% o8 h* A) ^# Z$ h4 e
+ n; _8 ~- W8 Z- v1 e4 ^" K$ P
maxmin的测试
  1. @Test
    # i' C, }7 O5 K) @, F- p; t& [
  2.     public void testMaxAndMinAge() throws Exception {
    ' v3 b% G- B( k+ O1 [( ^
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    0 w! v* l- G: D. `! B( L3 T
  4.         Person result = mongoTemplate.findOne(q, Person.class);( q  Q" ?: j" o: Y- |
  5.         log.info(result);* R. J' w+ B5 D+ M5 o" `' W
  6. . i2 _; r  {1 e0 e) s+ I" d; Z! b& B
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    , B( q" e, G8 m" }7 N
  8.         result = mongoTemplate.findOne(q, Person.class);
    ! ^7 [. B+ u1 p* n
  9.         log.info(result);
    ( i) n0 C8 L. M
  10.     }
复制代码
( y# \; H# w& t$ W8 z2 k6 q" [
1 t8 ^/ A0 m) h' m* E& l
distinct的测试:
  1. @Test
    2 f# X8 _* u4 _( k8 K: o: c/ M
  2.     public void testDistinct() throws Exception {
    , s4 g, ~% y: H) l( ]
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    & R2 v% x, f( h% ?7 \; V
  4.         for (Object o : result) {
      e" T) ^. y4 J' e
  5.             log.info(o);
      i* Y0 R0 G& v
  6.         }( `  l+ w8 P9 z" a- N- |

  7. / [& M! Z) `9 V$ o
  8.         log.info("==================================================================");9 p3 D. T: v$ Q' S( _$ _
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    1 K( n! w, T0 a# J# b
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());& l- {2 G( c' K# E
  11.         for (Object o : result) {' \4 U9 C0 E2 \& n
  12.             log.info(o);- A8 \' e% y3 J4 B: l& m; Q
  13.         }* H- R% V7 U6 e( k8 }; X7 t+ _
  14. & t3 D8 q. T  ?5 I, C* j
  15.         log.info("==================================================================");
    4 [2 Z; ^$ Q0 _+ I% {: H: }
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");0 w0 V! ^: F3 Q" Z
  17.         for (Object o : result) {8 T7 L* Y3 n, C5 C3 `9 y% }5 @
  18.             log.info(o);# j  C2 N0 P* O$ \( D9 N
  19.         }8 U' m( p$ ?  V1 _: V
  20.     }
复制代码
0 ?( \. h" T$ W% d+ ]) |
* C& i5 l: {/ x; v, |
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567" I# N' @" S  ]8 ?* \2 t. b4 m8 c
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    / x* g8 s( C- P
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    0 @8 o2 F5 l! c3 Z* H# h6 r
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
    * I2 [# C/ H) c9 }% H
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    9 y6 ?9 J+ l4 s# q6 t
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
      {1 |* \8 O; i: X$ i
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    ' n3 L. g% n2 j
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    % _( @  m: o6 P
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
      V4 k6 t. i( ]3 f5 e: _
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678$ r" D! n& a' n" B
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789, S( V  G6 z% Z6 _
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654" e  o# P  o6 R( M( p! B! o
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================- `5 w) b# m, H! L
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa5 _, n7 F* m: V! U9 e) N2 p% W& |
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    * v. G1 c: g# J$ r  B0 v9 q- t( t
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
      S3 S1 l" h" D$ x" S  [6 b
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    5 |! x% |/ M5 F4 V  W. k
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx3 l' M' l5 \. f! L7 S
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy& U' h8 c" t/ z' W8 e# T
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    $ r2 d# p# U: a+ O
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    $ v, A4 w* E' s$ 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
复制代码
' Q; A' E/ a1 H9 L. E% {

) i! @0 N! ~- S9 F: \- F7 G
这里我要特别说明一下, 当使用了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等信息。

/ X, ]( |, Z3 H4 i+ g8 J7 w1 A" |! W: L5 r6 e. ?

$ _/ E# m6 E4 A: X1 H7 j1 C" S
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-4-26 12:03 , Processed in 0.161719 second(s), 24 queries .

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