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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:% a0 L' s+ c" r- P, A4 \" `/ R
' W, Z, l2 N$ `& s
1 ) . 大于,小于,大于或等于,小于或等于
) F2 ~0 |- x( x$ o* ~8 B" I  u! b9 h. |# @! f' m
$gt:大于- z7 ~5 W' L1 D2 \
$lt:小于
/ M- `- M+ `; ?$ p$gte:大于或等于
& \6 S, o6 t6 f$lte:小于或等于% i) h  j- N: X
$ X6 p* o3 ^& x, B  d  d% ]
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value8 d  x, `8 W3 H. Q# E" A! R/ A
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value  n1 p% k  Y9 N+ t: i
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    : Z' d) |) [; ~- N$ z8 z3 V& G3 j
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

! q& G; F6 C8 ]* s( I
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});$ g: K) X% M3 j6 X6 ^
  2. db.things.find({j : {$gte: 4}});
复制代码

( {# H) j( n4 D+ {$ T! S! [; y7 e
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
+ f8 k& @) x5 b
2 \1 M3 |' @' Z9 A& \- Y; y' a

$ h( s: j; N5 b# z% O$ o
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
' n' E3 m+ S  R* g( i( h9 d8 C
3) in 和 not in ($in $nin)
4 n, L% i9 x! S: B9 e! C$ J' ~0 _- U2 Y2 a( [+ @0 ?
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

/ A, J# Z' f5 q8 J3 [! g
例子:
  1. db.things.find({j:{$in: [2,4,6]}});" d9 ~2 U# {- M9 v% Z0 o* p3 f2 Z
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

) C& _5 x& {9 Q1 {- i+ q. e
* \: {0 J9 r! U' B3 u; D
4) 取模运算$mod
1 s% r  H. h9 p  X
9 C6 X- X) e! h8 w8 p$ Q3 q+ Q: W如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
6 {; O) I7 i) ?7 g5 S* B
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

: Y8 D7 i) G0 ~7 @

$ K7 R" u6 Q4 R' S5)  $all9 w2 Q/ @, i/ d! U

/ b, L6 p# f5 J% j8 B5 _+ O6 T$all和$in类似,但是他需要匹配条件内所有的值:' f% M& [1 Q3 _
5 S0 S$ W9 A% c& x* s4 {
如有一个对象:
( V; b6 @# u- H% z  Y  Y$ B
  1. { a: [ 1, 2, 3 ] }
复制代码

* J" @$ {5 A9 T, I" m3 P
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
1 b; T; }) D# A6 f+ z8 v- `0 q, E
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

/ _5 g, T) g, F, y

5 S4 ]9 J! ^# Z2 ~" X2 Y6 ^: D9 d6)  $size1 r; g* e( z$ B7 B1 G; g* p
$ v, ~4 V/ }* Q( G' |3 b7 c
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
4 B9 T* W5 G: o' Q6 _
3 o! r- V5 D- w下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
2 \' F, f, l; \, p
官网上说不能用来匹配一个范围内的元素,如果想找$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.

+ t  @# u: D6 C( N" M1 s
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    % T) E: t/ u( r% H( @
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
% E0 ]4 I+ B. Z+ M1 V& K! x3 @2 v, b
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string9 K0 W8 v$ S7 e, ^: q
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

$ T7 w2 }8 s& h- L& A* ~3 r
9)正则表达式. |6 j0 _' L' n, \# Q4 g% n

( D9 ^/ J+ L' C5 ^2 jmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

1 [9 D& M( ~  ^6 l4 B! [
10)  查询数据内的值
& V. F6 J( u/ s* g" T7 Y
/ E( P; h6 R/ R- j* @/ T下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

+ I8 a# q% y% i- L% P
11) $elemMatch
0 E- o$ m3 R( s8 P5 |" u# Z2 n: |0 ?4 f% C1 t9 @
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) % c7 h2 O+ H" K, f! n" C
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  8 X, l; ]7 G. d& z' L) |! {, h
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    & I( o- P1 R/ b% t9 \# a% Y
  4. }
复制代码
) B$ S& _1 c  J- ]  Q  \
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
$ T# I# _9 D6 v- X6 U
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } % q; C; m8 I, [; j- j
% S- I6 N* o; V8 Z! p' X
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
9 f3 ~) _& w8 k# C
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

( l) k( e. g6 l# v, K  H1 p! Q
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

: U/ W% G: R, z( P4 H
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

8 C+ v/ U: v+ P( p  e
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

/ T) T" L3 s% |6 h1 J1 C! r: I
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
* z5 K6 c: ?3 d) S
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );2 i. p1 o: y% m8 x  g* Z% @0 C
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

% W! R9 @/ O& P6 {7 a
mongodb还有很多函数可以用,如排序,统计等,请参考原文。. h+ O. Q# y. x1 L/ h

$ h* K, h+ y& }. }  Q( Zmongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:- ~- t( Y+ w/ Z- H: V

6 a* J, C9 F1 O, U/ shttp://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
: P  }+ U8 @( g, d! V: }2 a
5 `' c1 j- Z  i) T1 W  @+ V2 [版本二:
) f2 `. p: ^: }) _1 M) S; p. X
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
- `8 y9 k( A$ g) k; C
  1. use admin
复制代码
1 g' p* F; `) s. @$ O" F
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
; ^+ \( u! ^8 t$ t- p( s6 e) @
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
1 e" i3 M, W3 c4 P2 @
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
* n2 p2 d  O& ?9 N7 q- p
         5. #删除用户
  1.           db.removeUser('name')
复制代码
0 N/ h2 I% _8 \. q, C9 a6 ^4 L. u
         6. #查看所有用户
  1.           show users
复制代码
- h3 M  ~4 z  Z1 \! f
         7. #查看所有数据库
  1.           show dbs
复制代码
/ x- A* j2 n2 E# w3 b- j  L* M8 @
         8. #查看所有的collection
  1.           show collections
复制代码
9 _7 _/ e, H3 e7 g4 M
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
7 z5 |4 [4 ^' N; F
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
5 z3 b# ]* B7 C0 L# Y
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
& I' ]6 X+ z& m
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

+ L3 z9 x1 c8 d- ^
        13. #查看profiling
  1.           show profile
复制代码
. a" t! J% _6 E9 K2 u! B4 y" C
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

6 r3 |1 H. N) v$ L3 u
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

+ F5 h! D: s; t
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

+ ]0 I) d. ~) M/ q
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码

6 B0 ~$ Y, B2 Z- ^. a
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
# L: W) B" w& D, V2 k! f4 E
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
; P3 Y9 V7 p9 T$ v: ?( t. B3 C2 P' J
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

' r2 t5 N% c7 o; `# c. S  @
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
4 \; @; F$ g& f4 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()
' A' }/ u' J) }
6.  高级查询
条件操作符 1 h+ e; B) @2 e* |' a
  1. $gt : > * O5 N% A# \! i( f6 }2 J* S1 l7 O9 o
  2. $lt : <
    " k! j( P. ^5 ]! C" `; Q& d1 n
  3. $gte: >= - Q3 E% i( t, O7 G* \1 E! ^' R
  4. $lte: <=
    : v: Q5 P% ]; ]( u: E2 r
  5. $ne : !=、<>
    . I; T/ p6 x5 V4 u( P3 w' o2 ?3 J
  6. $in : in # c& t8 H  Q& l3 m; p
  7. $nin: not in 0 v; }0 F6 m; `! b6 E4 k
  8. $all: all
    7 @7 R* I) f* v  e# f9 B. P
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
4 z9 f" z4 o9 l
4 X$ r' J1 T1 a, q' L3 t6 j8 L; a) |
查询 name <> "bruce" and age >= 18 的数据
& l: z4 ~% K: w
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

0 j: t0 l2 t, `
0 D# h5 J1 E* V, V. ~, T2 Z1 }' @9 f查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
3 J- E3 v4 W5 i; A' g
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

6 `" l) L/ ~  R1 Z% Z6 G7 c  |. w) U) z* W4 c7 x: k- H
查询 age in (20,22,24,26) 的数据
% \* i" r+ e8 I- X0 v1 d
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

- r( b# @0 c0 s0 C. r# _2 Z7 k2 Q( A4 n1 G" E3 ?  i* g6 A
查询 age取模10等于0 的数据 3 W3 C% Y8 L4 ~2 o# c
  1. db.users.find('this.age % 10 == 0');
复制代码

2 B& d' w) d/ B! t) T或者
6 s# }) X# L% o2 K( o5 _$ Z
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
  B# i) h( o% h6 ?( F+ v
# S6 b) O& P; P: J8 t" z8 s
匹配所有 " K2 @' J( w! j, h* a3 O% K- j
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码

$ g* e6 p1 C( i+ X可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
0 g' L! N2 T0 Q! }. w! S可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } 6 C: M% @& _1 a* k

/ o0 f1 I4 g$ V( P2 A3 |查询不匹配name=B*带头的记录 - h6 ?4 ?1 R0 K8 B4 e& f
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

* `  y# ]3 R) z' t0 I) Q0 |8 i查询 age取模10不等于0 的数据 ' U& |7 F) f% n% [7 ]% `
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

' b9 l  r: ^- S9 m7 {; K
$ ]3 w$ c5 E0 g#返回部分字段
- E. d7 A+ ~9 }; B, S$ S0 e选择返回age和_id字段(_id字段总是会被返回)
! S, s& g$ t7 p/ D& [
  1. db.users.find({}, {age:1}); ! c/ S- Q  d- o0 H8 u7 b
  2. db.users.find({}, {age:3});
    2 a3 E" s9 D8 t4 [- D- v# d
  3. db.users.find({}, {age:true});
    . N, L- q- D! t' \! b- G) g
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
( Q) C- q8 L9 w( L5 h! b
0为false, 非0为true
6 o/ @: x/ g. z/ R3 D4 B2 n
& @! Y, }* \0 Y9 s6 R  L) N/ u选择返回age、address和_id字段 # M( d! K# z6 j: f" X& `
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
6 i9 s+ W, Z3 M$ h5 ~1 |

* [) D5 Y& E/ f; @2 F4 k. B4 J3 z排除返回age、address和_id字段 5 z. \0 O; A" u) I* ~5 h  X
  1. db.users.find({}, {age:0, address:false});
    # Z2 y: S; c- v6 i
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
/ y# V  Z) h& `

& `" n+ H3 t& c/ B/ l数组元素个数判断
( \# L, ?+ U7 q& a1 ^. e对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 % O+ ^/ V: D/ v) r
匹配db.users.find({favorite_number: {$size: 3}}); & ]8 f0 S( `3 c% \, d% S" F
不匹配db.users.find({favorite_number: {$size: 2}}); 5 d" {. _2 b% @3 s' S; ?, _
- o( d- v* V. [4 t0 t
$exists判断字段是否存在 * M% ^& r- K/ P3 u
查询所有存在name字段的记录 & ~5 Z# W0 N- Q5 F4 b+ H
  1. db.users.find({name: {$exists: true}});
复制代码
4 t. q2 x1 @5 _, m
查询所有不存在phone字段的记录 ! P, e, t4 Q2 G$ N5 ?6 }6 E3 ?6 u0 q5 m
  1. db.users.find({phone: {$exists: false}});
复制代码

0 R' }/ D7 v- s- e& R
' n4 w7 u% i( V" `' q! y5 g5 _% x! ^$type判断字段类型
9 ^& G! Q8 J5 [4 L查询所有name字段是字符类型的 * b" p) Q/ F9 U2 g
  1. db.users.find({name: {$type: 2}}); + j% t+ C9 [: Q
复制代码

) P1 a  w! \- Z& s% H* z' K查询所有age字段是整型的
* H& g5 W% u' z' G
  1. db.users.find({age: {$type: 16}});
    1 S% s# @  Q6 W! }1 C" @
复制代码
$ t% Q3 m0 G# ?# u7 \5 y
对于字符字段,可以使用正则表达式
& b) ~6 R/ t( k' a9 i  o& n' y查询以字母b或者B带头的所有记录 & C5 G( z: W3 v! ~% _6 b/ U5 s
  1. db.users.find({name: /^b.*/i}); 0 S0 g3 o, h- h
复制代码
0 R) T9 e+ A+ G- V4 f; K+ d+ @
$elemMatch(1.3.1及以上版本) % }& b% w2 \2 J0 `4 `6 a
为数组的字段中匹配其中某个元素
9 X& \2 w# s9 T  M, P8 j2 v( M: i5 b" X/ x: g( b
Javascript查询和$where查询
( w/ J5 H1 i' x1 c8 `查询 age > 18 的记录,以下查询都一样
- l  n) f" l6 }* y3 v" x
  1. db.users.find({age: {$gt: 18}});
    8 q5 A* _" A3 ^* ]' q9 s% d
  2. db.users.find({$where: "this.age > 18"}); 5 i; R; c' J: T; R. K
  3. db.users.find("this.age > 18"); 8 a, w# |* F3 X: l; v' X$ _' N
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

1 F6 z) b# v; ?2 j6 N# H, j3 d0 O
排序sort() ) R+ q3 n  U7 w& `8 X: r9 e
以年龄升序asc
8 y/ ^+ W2 {# A6 ?
  1. db.users.find().sort({age: 1});
    : i9 T* @0 D, T
复制代码

; C" A  o. q/ h: I- `以年龄降序desc ; N1 ^* r7 \9 n: h2 W4 ~/ D
  1. db.users.find().sort({age: -1}); $ P  f3 L& q; n& K$ {1 H
复制代码
8 [7 E% M( y& |
限制返回记录数量limit()
5 [0 A: l. |5 l. t返回5条记录 # w# J  a" M/ Y3 l3 a/ a; l7 P4 K; j
  1. db.users.find().limit(5); . J+ H/ q1 r# v; y4 u4 c7 \: S4 V
复制代码

9 j( J; ?6 Z  _* s" p; I5 ^返回3条记录并打印信息
' r0 J6 x. W+ r# u# S# n( a
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    * {+ @* O+ W. b6 b' n0 {" f3 {  u
复制代码

4 |2 p4 E: A, @. ]+ ~  q) M( ?结果
6 [: Q  P9 E* k- u5 Y
  1. my age is 18
    9 X7 r7 g' r. y( }# N/ P
  2. my age is 19 8 Y; I. R! u* z& h' g
  3. my age is 20
复制代码

) c* L  H/ ^  ^3 @( Q& L/ C( N* J5 N5 D2 l  z& H
限制返回记录的开始点skip()
# {3 X* p7 W6 B, O5 {从第3条记录开始,返回5条记录(limit 3, 5)
4 E2 m' w& b4 K# s8 i" I
  1. db.users.find().skip(3).limit(5);
    0 {* p) h5 ]/ Y. b  G0 C
复制代码

: c: j7 a; P$ {0 ?; t查询记录条数count()
; `/ E+ ?1 G1 \3 n9 Wdb.users.find().count();
6 `" y) q2 A1 L# mdb.users.find({age:18}).count(); . \8 V, Z/ P& T+ x0 R7 s
以下返回的不是5,而是user表中所有的记录数量   ~/ G7 }, [! O7 G
db.users.find().skip(10).limit(5).count();
' c, g, o  Z; _$ E" ~如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 4 Q; `- ?7 J3 I  P# @2 `
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
2 [" `2 Z& z; p
; W1 x4 X1 D) U8 z7 e6 }# S6 G. h; Z
分组group()
% ?! x$ F: [5 V) i2 A( B假设test表只有以下一条数据 ' T: E) D" R$ N4 K
  1. { domain: "www.mongodb.org"
    ) ~" ?3 r: i! G$ r& v  o3 _
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} # S: Z1 y+ u; ^( u& a4 G
  3. , response_time: 0.05
    " m2 [( H, m( b' Y7 a7 }
  4. , http_action: "GET /display/DOCS/Aggregation" , l6 c$ s( d% n# K: v5 o5 a
  5. }
复制代码
/ n+ o- k: s; n% Z8 d9 X5 z  H6 }
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
- c  {$ [2 g: f8 B
  1. db.test.group( 5 a. J1 B5 y' Z. I! S' u
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} / y7 S  R9 u1 e3 Q8 V3 V2 _
  3. , key: {http_action: true}
    / F2 ~8 h' J5 [! y8 P4 x: z
  4. , initial: {count: 0, total_time:0}   @% N; b% C; g9 U6 M- O6 f8 M
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    ( g, S# z9 @2 z! X$ [
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    + e; q8 l3 P+ z; E- }4 _
  7. } );
    + q; X7 o9 k+ P8 A7 E

  8. 0 H" K8 s3 f- o/ `4 Y3 R1 c$ n
  9. [ / b7 h. l( B3 j5 c6 u) e3 _% e
  10. { 8 `; O8 m. D0 i0 m* u
  11. "http_action" : "GET /display/DOCS/Aggregation",
    - w& x) r- W. k1 x5 I
  12. "count" : 1, 2 G# N. P+ {8 L+ U* ?9 V6 ~6 N9 J# `1 D
  13. "total_time" : 0.05,
    7 |( c3 ]6 U% a+ U+ G  \7 ]5 n
  14. "avg_time" : 0.05
    4 P- T, k: `* z% T
  15. }
    . V  I# _8 i6 z1 N& U4 C: {; W
  16. ]
复制代码
+ V9 \4 D* y  Z1 |6 T0 Y4 `! r% s

8 u: N$ X- _( p6 ?8 v3 R
" |5 l! B) z2 k- ]: L  vMongoDB 高级聚合查询
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" a# t0 d) n: d! M) J
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
8 Z! Y! x7 q6 U9 }

; z4 ^. w% l/ Y% K; u2 A

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

) o- o- i2 C/ P& [
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

+ h3 \. H; V0 V2 N3 J/ L7 G
% p; d6 W# j  ]7 k6 @: U
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
% P( g9 {% K* |' s: \

  h7 L* z& e: }
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

' L( H. m4 P, |6 ?$ K5 }+ ]# g8 y. J7 K6 r0 C$ H
输出如:
  1.         1 B( I8 Z1 M! r8 `0 P$ k
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
( F0 V3 ]5 P" n0 V9 ?7 b
6 S+ x3 G/ j; s
! e, ?2 s* ~) @1 Y3 S  X- l7 O
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"# o: H0 F$ U" @: [
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance") U( t+ g! D# \$ J8 ]* ~
  3.        xmlns:context="http://www.springframework.org/schema/context"
      z4 C. K6 u2 v* [8 R# G
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"4 C, W+ ]* t% P
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans) E: m; A! t3 p% U9 [" J- ~/ R
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd+ q+ k- a5 ]& }
  7.           http://www.springframework.org/schema/context' p, p) d. N  l8 w* P* |
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    - y. X; M/ n/ R& h% R9 r: k' }
  9.           http://www.springframework.org/schema/data/mongo
    ( L/ ~7 U0 D% J) U( L+ L) R
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    $ H2 H: ^  N9 s7 M5 ?4 v3 |
  11. " q; M% ^2 w% J% m3 {) c! a
  12.     <context:property-placeholder location="classpath:mongo.properties" />7 y0 u8 m. X' n( ~' {  h0 f

  13. 5 j- y3 [8 u9 z0 l/ }8 ?1 K* e3 O
  14.     <!-- Default bean name is 'mongo' -->
    ( L$ ]' Z. E3 _4 X
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />! w- c' ^  s2 B7 W! e

  16. & L! _+ `3 x( A6 D
  17.     <mongo:db-factory id="mongoDbFactory"
    ) l) Z3 P/ w* q$ U8 [' w
  18.                   mongo-ref="mongo"6 y/ f3 e+ y& i2 J$ k
  19.                   dbname="mongotest" />
    ! H6 h/ h6 _8 q2 G0 C+ C
  20. - V- F. H% W4 |8 Q; ~- k
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    ( y  v! A8 q3 Y4 z# x
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    ; b) y2 c$ I3 I
  23.     </bean>: ?% o8 P  P& e
  24. </beans>
复制代码
# G2 }# r7 W- V9 b+ A# N% }) g1 }

, S. X! U' @* X7 t, }
maxmin的测试
  1. @Test* d' v2 P( k2 c/ c- B/ p+ q, k# X
  2.     public void testMaxAndMinAge() throws Exception {
    0 h6 b' A/ o$ S
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);7 C0 R" @" {2 a
  4.         Person result = mongoTemplate.findOne(q, Person.class);/ |; t0 L8 a, x: z
  5.         log.info(result);
    6 z/ @& Q; N/ B# H
  6. 6 z3 U2 z' @: j. N) P! i# S
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    # M2 m3 R# M- u& B
  8.         result = mongoTemplate.findOne(q, Person.class);
    5 U* ?/ K7 h0 K- U, R
  9.         log.info(result);
    4 N: q: A- y7 |
  10.     }
复制代码

" a+ w- q4 Y: c% |4 D9 }) p: t! l: _( H
distinct的测试:
  1. @Test/ D2 w% [/ S# {" \. P" ]3 l( G
  2.     public void testDistinct() throws Exception {
    $ _/ F( A1 n. V$ w! n# X
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    % X7 u3 e2 z% D6 F/ s1 ?' B
  4.         for (Object o : result) {
    # U. F+ h0 Y3 l! E3 E
  5.             log.info(o);+ v0 L+ B- i1 ^* k4 G# y# Q
  6.         }2 y2 q* w0 b" N# |% r" a9 W

  7. " [: b5 }+ Z0 I9 D: W
  8.         log.info("==================================================================");2 k  N, M1 |( q) e8 b
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));+ e8 T2 N& g- a7 d
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());! b1 F* E/ N8 P& N) F  T' D
  11.         for (Object o : result) {
    & Q( d# X7 @1 i2 A2 t
  12.             log.info(o);+ f/ A2 I9 J( g3 ]& \
  13.         }& \3 ]8 s  p* ^. N" G1 @) ^) p

  14. 0 R* b5 f9 I; T& q
  15.         log.info("==================================================================");
    2 I# X7 z, B0 d+ G5 J% y
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    & [$ z. N; B$ q# k- `; U. K, i
  17.         for (Object o : result) {! S4 O  z4 j& D' p* S
  18.             log.info(o);
    * N, I% i* Y' }  k7 z3 @) r$ y1 i
  19.         }
    5 o& \8 W0 u3 R1 e8 N5 P
  20.     }
复制代码
4 T9 s& R: S1 ~$ H% v  B+ {

/ w' J3 R5 Q: g' `
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567  c! c$ S+ V. A5 W8 j3 g4 S5 I
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    3 H5 ~( _& [: {7 G9 j# j0 Z4 |4 I
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789  b* Z) ^, l5 P# m6 t2 \9 \
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 9876545 ?4 i5 q9 D8 m6 x
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni; ]( u- H( A; M* l1 U' {
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    5 h0 k0 d! h9 i% m
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456$ n  O& `/ p3 j, ?
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    # b& h9 u6 A/ d6 y6 I0 z
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    % v# f2 U" B- W4 F7 _6 k0 N+ z
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    & z3 e* G. D' {2 s1 w
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    8 \0 S1 l4 ]( Y2 z( L7 Q; K
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654$ X6 S6 ?/ Y2 r; A% |- T
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    * r/ Z6 _/ x( v3 z& {! B
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa. R% ]  g7 [& e9 c  D/ M2 `2 y
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    5 i( o, U0 r( ]4 n3 O
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc. v9 l" C0 t+ v7 x
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www! Y) |" D4 s  T, s' m
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    1 q7 X; I! ?* S
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy% f! D! ^$ i$ x) J0 [
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    4 F6 K( j( E+ n
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    5 M3 W, k6 f% `+ J. e
  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
复制代码
) ~! }) z3 G  ~8 f# p- a7 @* y
/ }0 e" e7 T$ M/ u- U8 o) w9 {+ m
这里我要特别说明一下, 当使用了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等信息。

2 |& C1 f- V/ V( K) X/ q# a$ e5 c2 K

: p. s6 v  a- c" [7 m
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-8-4 10:10 , Processed in 0.070460 second(s), 22 queries .

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