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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:
% @( Q* H& h6 o. K
& s, w0 P% s/ \1 ) . 大于,小于,大于或等于,小于或等于
" w1 p6 U) s& o- m; J5 A2 N  E- P, j
$gt:大于
+ u% C0 C0 K9 ~+ M) Z$lt:小于
9 x4 @% w5 o- o  A/ [$gte:大于或等于1 t. {- g/ P; b$ l8 l* J! q3 x
$lte:小于或等于
6 b; f0 R: m% o( I2 \+ E
2 E7 R6 j$ z4 F7 s4 o9 i3 _例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value+ K, P# R& t9 A- H* L6 ~  t
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value$ w1 Q" V. @8 Y5 R
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    * V1 c% c1 u7 }5 z8 h! m3 n
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
7 B) C1 n4 t0 {: U) o
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});' Z2 }5 k3 I$ C( p6 q! ~
  2. db.things.find({j : {$gte: 4}});
复制代码

& l! f$ d8 [. y8 Q* L1 s
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

! e8 m- x' a# e- f  A5 i, r5 J2 y$ k  c8 l) W" X4 [

  H0 K! @4 j' h% E
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

2 e" O7 p" E& E2 c. K8 E3 ~' Z; n
3) in 和 not in ($in $nin)
# {, z- r7 Y+ y/ I6 Z9 _; x; K1 {7 V" J
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
  x' j+ ?6 Y9 a6 b, D3 ^
例子:
  1. db.things.find({j:{$in: [2,4,6]}});8 H7 Z3 [1 x( r& h* ?
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

! |' ], o4 e5 \$ U7 r4 }+ Z& h$ t
' J- N& V  B: E' ~4 k, ^+ d% K
4) 取模运算$mod
1 ]% _9 D8 i- ^; T, n/ y3 \& a( s
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

- d, F  ^+ d) U5 Y. \' |+ H; @
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

( Y3 Z: X% @- i; A" m' C
) s6 d1 A0 A1 F3 m# r
5)  $all; [0 w8 f- N; G* h' `: Z
8 p/ A  b* Z- C* W  f% J" E, w3 L
$all和$in类似,但是他需要匹配条件内所有的值:
% c6 M5 X& D% {% Q. y
. u7 M' W  t) g/ q如有一个对象:. H+ i0 g* M: l! m& k
  1. { a: [ 1, 2, 3 ] }
复制代码
+ s! b# S2 S, z8 B2 l
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
. Y5 N/ m9 c1 n: r
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

' d7 O6 i2 _/ b6 G7 J! ], ]2 ?0 W6 u5 s
9 T8 q' O2 c! v
6)  $size! n! R' [# E  s" Z* ]" I

/ K0 ~/ {4 O+ t$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:3 G1 D" {& K/ O8 }; w' ]" l6 a* T
6 h7 m, g9 s/ e2 x
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
6 c+ Q7 ?# A' d
官网上说不能用来匹配一个范围内的元素,如果想找$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.

, q% M4 j) W; |
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    3 R4 k# H# q& L/ E9 o+ Z
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

+ _% N- d9 h: |: k3 Z% }1 s& ]3 U- M; N2 A
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string# U8 ?' W8 M5 J: r6 Z
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
3 n/ `- I, f7 a$ O) F9 i
9)正则表达式
# ^  J  j! W# I- P0 }0 s  Q  F1 b; q% K6 K5 K
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

2 X1 T: W2 F2 ]- s5 Q
10)  查询数据内的值
+ X* @9 X3 \, z- ^; y* v$ l
- V8 A& T/ @. O; o/ X+ n下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
$ F& }  u& z7 b/ D( {
11) $elemMatch
/ H0 G9 i# I, Y( l" K9 G
2 k+ y9 A: e; l; F如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) ) X7 K0 Y% H7 `' [+ s' c& h$ ^
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    2 @) W2 D. g$ v4 D; F! ?) m' L4 ^+ |
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]7 Q" x' C% ~0 P& s  ~8 i6 L
  4. }
复制代码
* X* @& I5 Q8 m9 W' u5 p
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
( P: f* j  I  P( }3 N
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
! c8 M: O7 ~, e5 M  P9 h9 q6 G+ K$ l- m- f: L5 \9 f" Z# S
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码

9 y0 n! Q2 q" U  ?, a
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
6 I( h3 _6 L( E6 I8 z
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

0 |# P1 B. O+ R% @: }4 s
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

- T- a! R3 p* f" i
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

- J* L- ~; t  ]1 B& L
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
9 e" f5 t' e# {5 }  Y
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );2 Z0 v4 I8 l2 K2 P0 J0 G8 ?/ f5 u, W
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
; {' I' ?4 u0 b, l# U/ J  f+ h5 a% J
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
( s" O+ K7 N4 N  m$ ]# e
( {% o/ ]& \1 W; Bmongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:! f* E. K; b, }9 O
' x3 ~2 g! D8 F$ \3 t
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions/ e& j2 o$ |8 X1 T
5 _. v+ l7 a7 v* A5 n- R
版本二:
$ m& w% d) s' ?7 Y0 E
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
9 J' c# g. M! _. N$ |
  1. use admin
复制代码

* N9 v, [" t4 q0 V" Y  b/ |
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码

7 F: K' A6 F' B$ I9 O, g8 v
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
( G7 r4 w( ~! b$ v, x- U# _& n9 ^
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
. G6 l1 A5 e  }6 M
         5. #删除用户
  1.           db.removeUser('name')
复制代码

4 ?+ q( E; [$ K0 B" L- B6 W
         6. #查看所有用户
  1.           show users
复制代码
3 j0 A1 u' C+ R" J# z2 H
         7. #查看所有数据库
  1.           show dbs
复制代码
3 K: [9 [2 |# M& @
         8. #查看所有的collection
  1.           show collections
复制代码

* y8 R, T; [1 W' s1 i
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
. B9 Y! ^0 |7 Y) a, G: C8 g
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
' l" |$ X3 y) d2 @" k
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
4 q, X0 l1 w( U8 Y9 e4 F
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

7 g# l% L* l4 S9 W
        13. #查看profiling
  1.           show profile
复制代码
/ z0 c! g  S0 O7 u
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
. P8 R! M5 @/ G4 B% D) L& b3 [" [
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

, @% r4 b( b# O9 E8 [1 @1 F
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

5 ~9 ?  H3 B. p* s) t
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
9 a4 K7 L' {* l
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
) e$ g% J$ S% K* ^( K! E
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

) [; e2 X; X6 k! n" ]
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

0 Y" v+ t% T* b) m* l% `
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

9 w0 d, u5 V# U: e- k3 t3 u6 _# m
   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()

9 B3 H' Y; F- ~5 m9 @! D
6.  高级查询
条件操作符 - p( O2 y7 o$ Y3 ]$ l
  1. $gt : >
    9 q, A5 E8 l+ C
  2. $lt : <
    $ M) k" K1 g0 d* ]0 Z0 |6 _/ R9 n" K
  3. $gte: >= ( O* m  ?9 d) M2 p5 F5 i* |
  4. $lte: <=
    " J* _: D* m9 P0 a
  5. $ne : !=、<> 3 f! d5 F9 y, P, f
  6. $in : in
    - q! ?9 |3 a- J2 q: V% X" f5 n
  7. $nin: not in ; |, x  J% V( d6 a, x- N* r
  8. $all: all $ f7 s  M7 N& v
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
! r: ?  R' A0 U7 N1 k( }& |
& L- M0 }% q+ |. k3 N% q4 K
查询 name <> "bruce" and age >= 18 的数据   a1 O2 o1 R- H8 T: L6 x. {
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
  r6 u2 t* B2 C& h  L7 [

5 M6 I$ I8 g( B# Y' Y6 w. e查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
8 O& I. W4 ^7 r6 @  N& n/ D
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
$ i7 n6 `4 a% ~+ \
2 g- a( h6 k  q4 C3 W, q
查询 age in (20,22,24,26) 的数据
& C  x: f0 q4 l% T7 B
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

/ @8 g3 x$ S0 A9 M, m# A, N
1 Q7 V( {1 _* P7 i查询 age取模10等于0 的数据 & ?0 Z/ V; i/ Z8 c
  1. db.users.find('this.age % 10 == 0');
复制代码

& J; A0 ^' M3 C. t$ S: `# S或者 " V5 W& L& ?! b' k% x
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

: B9 I# v- ^8 h9 Z0 \5 i4 s7 \9 H
4 U) [# W  M: w+ e$ I; h匹配所有
1 Y5 J0 ~! \: i! a
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
' X1 y% v: }5 p
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 0 Z' _' ]5 x3 e3 E
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } $ C2 i! N8 l/ k* Q

" Z' L2 c& M  M( q2 V2 A查询不匹配name=B*带头的记录 7 B# F, A9 u. p2 i' n
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

% S$ u5 ]! E* W3 Q1 x) Q查询 age取模10不等于0 的数据
! B/ s7 l) B1 S$ P7 H2 d
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

$ D0 q  J* b# l' x6 B6 J, b' W
8 y9 C9 Y$ C' d  R#返回部分字段
( |. }9 u) B! b5 Y4 v; Z选择返回age和_id字段(_id字段总是会被返回)
" F1 x# ~1 f! u( T, t$ `) k
  1. db.users.find({}, {age:1}); $ ]. _6 }& C8 k) {" h
  2. db.users.find({}, {age:3}); ; K* X+ r( P6 d: w+ |; k
  3. db.users.find({}, {age:true});
    ! E% B" P' ?* A! a# F
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
8 D& y/ A# ~! T1 [9 d
0为false, 非0为true ! t; g# s4 I2 M: j; ~* @
6 @$ T; g2 Y& B' B! K/ G
选择返回age、address和_id字段 / E. ~( I! q  x3 N
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
* t8 ?( I* V* O# }0 N* D1 P5 n
0 e  S7 R: ^; D8 Q) l# C- S* M; W
排除返回age、address和_id字段 3 D  o3 I; {4 ~: R5 x: o
  1. db.users.find({}, {age:0, address:false});
    + E1 c4 s. ?8 t( J, s( E- H$ T
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
  f4 t5 _% g; ^

- P1 D" x' R$ f% H+ s数组元素个数判断
) [5 V% g4 ?0 a& B对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
- l# _% [3 [" V匹配db.users.find({favorite_number: {$size: 3}}); ) \3 }8 \$ d9 s
不匹配db.users.find({favorite_number: {$size: 2}}); ) w9 c6 u2 z) `% Q, P1 V
" q; k% T9 d$ H5 b" A' \# b
$exists判断字段是否存在
- f3 n+ Z# `6 G: i' L查询所有存在name字段的记录
% M3 w1 W  J' b3 `6 ~3 _7 I
  1. db.users.find({name: {$exists: true}});
复制代码

0 T- e( \% h: L' ]' R5 E: V查询所有不存在phone字段的记录 9 o6 {9 D. l! e0 q9 o1 }
  1. db.users.find({phone: {$exists: false}});
复制代码

6 C* e5 ~3 s) Q+ b
" q& c$ X$ `* v1 s8 T- i$type判断字段类型
5 l: O/ U# p/ H: x' g4 Z查询所有name字段是字符类型的
2 s; l* O5 O" v9 {& z- {/ m
  1. db.users.find({name: {$type: 2}}); ; Y! w' e, b# s3 g0 Z
复制代码
7 d/ Q% T7 C2 o0 g/ ~6 m
查询所有age字段是整型的
/ {& [8 L5 J3 G* `+ Z
  1. db.users.find({age: {$type: 16}}); + L1 K' \, S5 y) e# z
复制代码

2 V# F7 ]$ e* q- C5 c, W对于字符字段,可以使用正则表达式
) k( Z9 A8 w5 U4 @7 A2 X- d, Z查询以字母b或者B带头的所有记录 . ]! A0 O# d8 }$ q" j
  1. db.users.find({name: /^b.*/i});
    - O8 J8 F" q+ {' k+ x+ B
复制代码

7 Q8 F; V: j- \# \8 J7 b; k) P$elemMatch(1.3.1及以上版本)
2 e; w, ~1 V. [. d4 Y为数组的字段中匹配其中某个元素 : S/ C$ O) ?5 \! c6 q, y/ c
# W$ Z  S/ g% {  X! t* ]! S4 t
Javascript查询和$where查询 ( g! D  E) y" U! b
查询 age > 18 的记录,以下查询都一样
) X3 @7 o5 ?) N/ E3 l( S0 Z
  1. db.users.find({age: {$gt: 18}}); ; h. O/ M# O2 y1 p5 f9 _
  2. db.users.find({$where: "this.age > 18"}); : B* \- K* G& w4 P! |
  3. db.users.find("this.age > 18"); % ~. F* B7 |' m4 N
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

: s; n" o. L5 c) t  a
' [! f' n9 }& \! N排序sort() & D9 Q, w% c: u5 L% j* k& k
以年龄升序asc
! F  p; X* O) b& H5 n- n
  1. db.users.find().sort({age: 1});
    . k8 H5 [& l6 {# h
复制代码

2 M7 _+ f, H% K0 X以年龄降序desc ) C# `) d+ h- Z; H2 {' G
  1. db.users.find().sort({age: -1});
    ; t1 `7 q- z! G: R; S4 M
复制代码

& S; g4 k8 i" T0 ?限制返回记录数量limit()
/ ^- [/ B+ g# g3 M. B返回5条记录 ) c7 b$ `# l1 X) W3 M1 O6 G) A
  1. db.users.find().limit(5);
    + v' Y! |* g7 E1 V
复制代码
9 s" D5 d7 x! ?( w0 d% A, C4 K3 p
返回3条记录并打印信息
6 t0 M5 E, Z* Y6 U/ N
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    : U' T4 j6 w9 I7 H7 x2 o" U
复制代码
0 S8 j$ P  ^/ I
结果 , f; l2 E' ~$ Z, Z6 Y0 b+ f; A
  1. my age is 18
    3 e9 i+ ]& _# S
  2. my age is 19
    0 o" c4 \7 U; H/ J! Q( ~% L* v
  3. my age is 20
复制代码

$ S& o+ U$ R" q% _6 N% X- O6 W7 r
限制返回记录的开始点skip()
7 j2 r$ S7 u, \从第3条记录开始,返回5条记录(limit 3, 5) ! e. T1 z2 H; }% a1 t; n6 H
  1. db.users.find().skip(3).limit(5);
    ' B( c& i0 w  m6 k3 t
复制代码
- h+ d6 O* V' `
查询记录条数count() 7 x  G" F- e! A* O
db.users.find().count();
& s8 d% u/ u1 B; |4 D7 o+ t: ~6 Vdb.users.find({age:18}).count();
- A5 X9 P- `5 v4 I+ B以下返回的不是5,而是user表中所有的记录数量
7 [0 M* O: R8 vdb.users.find().skip(10).limit(5).count();
. `' w, s" c8 d7 }4 M( h5 i如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
5 b. B  c# `2 K7 q1 `
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

% f) R" V4 z4 G: H  D
/ @8 n$ X( y/ u1 o分组group()
& g: o2 l" N: \- p. Z, @0 i假设test表只有以下一条数据 1 p2 l$ R$ b" D
  1. { domain: "www.mongodb.org" # C; ~' J4 h, V+ D* z/ I: ^% M
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    ! Z7 g5 Z5 s0 s- |  r% m5 f/ Y, f8 ~
  3. , response_time: 0.05 : q7 K; m1 h5 N& C
  4. , http_action: "GET /display/DOCS/Aggregation"
    0 ?" x- x+ T7 i) H
  5. }
复制代码
' O* p6 \% H$ U+ u0 R
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
% x- g2 R8 ~$ N6 n5 {0 Z
  1. db.test.group( & X" D+ a  T. F
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} 9 {1 A- }* P2 n) C  L1 G
  3. , key: {http_action: true}
    5 O2 M+ Y" R) n" _5 C% C" c
  4. , initial: {count: 0, total_time:0}
    $ H  Q$ L' `8 W/ h) \
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    & G5 O+ [" C: V5 Y4 P7 d
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    $ {# O4 y5 o; Q5 K4 N9 S
  7. } );
    7 v# |- J$ i. u  Q, G. J
  8. + R' ~4 i3 Z" O% m% I; v
  9. [ # e% I$ k/ M. q2 Z
  10. { $ N/ ~' H- J1 o* u
  11. "http_action" : "GET /display/DOCS/Aggregation", 3 M& @) ~5 Z! s/ \9 @( Y: c! }
  12. "count" : 1,
    . M# h, {1 ]0 B: q1 X% F
  13. "total_time" : 0.05,
    $ H5 i5 t  w, C8 ]. S5 ?. d3 t: C
  14. "avg_time" : 0.05
    ; B- N, e9 N( u9 }6 e' F3 y
  15. }
    0 a8 o+ u' R0 ]+ X; q( J' ?6 H' q) ~
  16. ]
复制代码

! i, b9 c& U& t, R8 E
9 Z* U' K$ v6 }! L* U8 D8 Q! c
- ^7 U6 {$ V4 n. C1 V( pMongoDB 高级聚合查询
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
    $ u: [+ U6 m9 O7 L2 O
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

7 w$ N7 M, }1 F3 [, u$ m+ C- Y" E; J2 v7 Z" S% S

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

7 X& y% f# [4 n5 k. O1 K
' m3 a+ F+ v4 P/ t7 q
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

, W! R- _% `, K3 \- q6 k, g& P6 ]7 {3 w, K% _0 m- O2 w( L$ k+ p! T
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
; D( z, M) `! V- x! H
. K# K' v8 e8 X( d  [0 f
输出如:
  1.         
    4 u7 K) c3 O, H5 ?8 r
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

8 b) M) Z: e* g2 y- X! Q! J4 I5 d5 S. y2 m; |2 ~

1 c) G& s% O; w: z5 @" q
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"6 M2 [: w, Z+ V) J* W" x
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"3 y3 ~  F# S" l) N; b! w
  3.        xmlns:context="http://www.springframework.org/schema/context"! F5 V7 c7 `8 z3 v1 L
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"7 m9 z, Q# y0 ?1 x" J2 Z8 I6 Y
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    / T5 y9 o1 `; {/ {3 c0 n7 w. d
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    ( A; B2 V1 h3 j- Y' x3 Y
  7.           http://www.springframework.org/schema/context
    6 P, K1 X8 G# [- h) a4 r# S
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd# _' ]& G* L3 }9 f) C) y- b
  9.           http://www.springframework.org/schema/data/mongo
    7 E# Q  f; f3 }# u$ V
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">! q& g. D5 p* J9 ]9 ]% [. U3 E

  11. ! H! v, r* R1 {  U
  12.     <context:property-placeholder location="classpath:mongo.properties" />* q1 k4 U1 |3 P4 |9 r; {
  13. % |4 S8 @3 E& X
  14.     <!-- Default bean name is 'mongo' -->
    " l. X+ m* |8 X0 Y0 o
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    ; i$ _$ ~8 R) x: |/ H& r4 y

  16. 7 u* j0 }5 g0 M. D. Z
  17.     <mongo:db-factory id="mongoDbFactory"4 s9 Z$ r+ V: \& ^2 h) I
  18.                   mongo-ref="mongo"
    . m; T) z2 o( }% q
  19.                   dbname="mongotest" />
    : ~1 M: H$ A# \. W$ \
  20. / t& `3 d; O, r+ K. J+ F, w
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    7 t) ]# n9 h3 r) `
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    ' b1 ~/ O1 ^  J! J0 I9 g$ L' E+ g
  23.     </bean>; F; U3 e. \! M2 `- Y7 \! b2 T- |
  24. </beans>
复制代码

7 r/ v% k. h; w0 g( L; P2 ~- z. r# I" c

9 X- i/ M3 U5 D, @
maxmin的测试
  1. @Test, r6 m2 n5 ~6 F6 k  V4 a
  2.     public void testMaxAndMinAge() throws Exception {
    2 o, L% x7 ~! e$ _3 p0 I0 R
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);% |- W, T8 B* v  Z& U6 z1 i
  4.         Person result = mongoTemplate.findOne(q, Person.class);9 ^- Y( |( _' c2 ?3 S
  5.         log.info(result);, Y( k4 w+ R5 u1 X

  6. % {7 `2 U0 b. i  Z% i6 ^% ?% K  _0 t
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    7 r! O9 N& t7 f3 L+ `1 E
  8.         result = mongoTemplate.findOne(q, Person.class);' F2 p8 t9 E2 O9 g4 M
  9.         log.info(result);
    ' P! s. N8 y- s
  10.     }
复制代码

5 T! ^. r  O: \! v1 T3 z1 C" `4 O4 H. W7 e; A' F6 w, B
distinct的测试:
  1. @Test* I5 o; t, o+ t' _* P9 ?3 p! z
  2.     public void testDistinct() throws Exception {7 p# Q9 E- ~5 o& \
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");7 r! p1 |8 `6 a. R5 K: o
  4.         for (Object o : result) {
    ( G- w+ A6 c' {5 M, E% w
  5.             log.info(o);; g7 O+ D# ~9 Q. P0 E7 U
  6.         }
    - d& `; p, D. c4 ~2 S3 Z! l8 y* w
  7.   j4 K' o, e/ o' F. |0 j. h
  8.         log.info("==================================================================");5 h6 O7 U5 v) i% {5 n% t
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));' `) U1 c7 U. {- B! J* T5 K: f% p# U
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    * Q$ H: V, r& g- [% \/ H
  11.         for (Object o : result) {
    6 [# G5 \- ~/ ^) ~' d/ t
  12.             log.info(o);5 z# [; X! l& I9 M! G% e/ n
  13.         }
    ' p% t' ?( H9 J) _! L

  14. # O( F$ Z0 p# ?; b) G0 L
  15.         log.info("==================================================================");
    ! m; \$ h( P# ~0 v: V
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    * Y' [) a7 k) r7 ^/ u5 {
  17.         for (Object o : result) {
    1 S: P( \( ?/ _% T& X
  18.             log.info(o);
    / |/ D0 p" G+ z" z
  19.         }
    ! z  N) [5 D& ^
  20.     }
复制代码
; q% d2 R' Q7 _' ?2 ^8 u
; k* t8 p+ `& L2 z* r6 s2 ~; f
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    - Y6 ?, P1 I2 F1 G
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678  D  K* A4 e0 K6 b
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789) C5 ^* r- v- J7 g
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654% ?% s7 j- n" E+ Z) A6 C! a
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni) f/ T$ ^0 x* ~  r- o& L  v: K
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo5 S, H: U, x% |3 X
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456, {* F- h$ s  Z6 b
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    0 w6 @  _% L% i0 c6 e8 w
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 2345676 i  I) i! M8 ^/ F: b6 j
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    " ~! ~* L- `8 m
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    3 n5 }3 W- ~+ C: w: P8 s0 D2 {
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    " }3 @5 _/ G: Z+ }! X! Q
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    . s; D/ Y1 d, i% f6 ]7 e
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    # A$ R$ s, ^" X+ H- b
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    # q- A* }# l  |3 Y2 F) U
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    : Z5 y2 ?( q/ ^- {, R
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    ) X: r# {2 x: X6 [6 A
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx( _# o" F, Q0 F! S* C
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy4 _* J' @- Z# S* O8 Q! \
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz* F: @) J$ ~- i  B& }3 O& x/ Z/ D. |4 S
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr' d7 o9 i+ S- ~6 Q/ r
  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
复制代码
1 V" G0 u& q+ F9 ~" f7 |
' {* Q! X( {6 V) f' O5 c2 l
这里我要特别说明一下, 当使用了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等信息。
6 n% ]3 k1 k$ R/ D% q( p
- @) d- o2 M! R* e
6 `5 q$ C, T7 [* V/ M8 j7 {- m
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-9-21 03:11 , Processed in 0.064018 second(s), 22 queries .

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