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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:3 b! C% x7 K- T
+ X: o5 h/ z9 \$ b
1 ) . 大于,小于,大于或等于,小于或等于
; q# a- w2 b* a% c# ]9 f- t* P# D
% ], ?3 {, m" |) {* j$gt:大于- ]6 z( B! K( C1 J( o" d$ H. D
$lt:小于" y+ C' a% s1 P8 d. V+ W! `
$gte:大于或等于9 T  r9 \, Z. x  j6 R( i
$lte:小于或等于
3 ^6 J7 n1 i; a% Y( ]6 i
  n( J7 D2 o( D/ b/ C" e0 p例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value) E) ?& F+ r3 l5 ?: d0 U& H; j6 Q6 B; A
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value. i) Q5 D/ D$ E) ]% ?. X
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value) m* {  I& U0 P
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

5 J0 {; [$ t0 Z( p$ F. T- s' G
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});0 y" Q! X" h- d8 m# b( R! o3 ]) o3 X
  2. db.things.find({j : {$gte: 4}});
复制代码

. v5 W, ?) _7 G3 p# Q
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
& C! V' t3 f/ a1 V' k+ u  f. G

* V6 Q" V. C7 ]! k( `
! U- T0 j0 }# P; R: |
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

/ Y2 t: Z7 l: i' T' s) q
3) in 和 not in ($in $nin)
5 _4 a6 @/ N/ ?: g" y7 K$ l+ Y9 a  [; h( b
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
' b$ A. q4 Q7 U7 i/ G% T
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    0 U4 L$ g  Z7 }
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
: W( _* ?5 {4 A- P

0 c3 V. q3 l6 w5 @/ [  m2 X4) 取模运算$mod
! n" V- D2 u, ]1 ]; C  [  T) _& D1 [, O' v1 Y
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

& a6 W9 v3 M0 k1 f" T! A" b6 c
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
6 ~* _& f4 c4 J' Q

3 m( T( n) o4 c* F; G& e) }5)  $all
; [3 ~2 `) J# U! o0 l6 R3 W: m. I$ O# F1 o1 O7 y" i9 x5 z
$all和$in类似,但是他需要匹配条件内所有的值:# s7 X- U9 ?/ R- H% d; Z4 n
/ e' O+ I! y4 Q7 a' Z  S' u
如有一个对象:1 A6 Z  F# w, q) k1 {1 V# f% T& L' o
  1. { a: [ 1, 2, 3 ] }
复制代码

$ C  h+ j6 F7 P
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
9 b# B2 T2 i& k. {% z% t) r# U) t# f
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
7 Z2 Z% ?6 o+ M2 O8 D1 m

' S& R4 M% V2 q* _7 K- Z& v  O6)  $size
0 F$ a: ?: \; ^. v( G6 K6 p7 g4 c$ t# c: H$ c
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:  @1 l' I* k8 U7 t, m" I- b
( W) M0 g- l6 S* T8 ^  L. {8 X" o
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

' k! s7 d2 D. C0 O
官网上说不能用来匹配一个范围内的元素,如果想找$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.
+ Y6 c- K% B! D0 m
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    , Q- J. H9 B( K5 J6 Z; X
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

! A" A  o- [# j& G8 p9 |
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string$ J- M7 }/ \  h# s0 Y4 c5 M. S4 Q/ s$ Q
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

) }% }: ]; b! O; R  y5 }
9)正则表达式+ j) c# ?7 [" a! |
5 @7 Z- V# ?: t+ c6 Z
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

1 }  T0 P* I: b7 g' m7 u1 n
10)  查询数据内的值. k1 @# g5 C/ |' f3 u
! \% r1 y; v3 m8 Y6 Z. A
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

, v/ G3 H8 }$ ~! E( U1 I
11) $elemMatch
7 R% {; y- g0 Q1 z3 Y0 ^* [
4 q, L# O) U3 o如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    ' @( T. L# q& j& e
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  + Y+ H+ W7 x; {' p! N3 V/ ~+ v' |
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]8 X, U  d1 C) Q( A  _! K" n/ S
  4. }
复制代码

: M; e8 c% M5 P; B( M8 y2 Q) I$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )1 \4 @3 Z; L: S/ ]1 C4 V4 |  ^- i0 x
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
- |, [) X  y: i" ?2 |+ F; r' h# a) k- b5 _1 L8 W
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码

4 d7 ~3 V& x, y5 M: ?; c
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

+ T8 J, l7 l' @. j' }
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
; z! Z0 L  T$ N- m
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
/ g: m# A/ P! ?, g! C
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

6 F8 G8 {7 O- n5 T
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
) e: d+ o: o6 _# @
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );
    4 r; n0 N% c7 U; i1 W% h( u3 H
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
1 V9 i6 ~' R  x# J  G) V( T+ [
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
- t+ O  V9 R' }8 c. |" O2 w
5 A# [! A' @8 j) @mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:3 S' z+ _7 f& L/ L

# P1 m+ @* u) M6 }5 @  P9 K1 b5 L& xhttp://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
6 P; C5 n  g, g) ~% x  o6 b9 R
* a, f/ e* `& a7 S. H- M5 b: H版本二:# G: f1 z" U# K7 t/ |" z* j
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
2 z, S3 c" P+ l0 k+ H8 z
  1. use admin
复制代码

6 }4 W" c, @1 \! i) {# D# i* V
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
9 C. _7 Z) W" p
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
5 O0 p/ q$ @; {% G
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
, c) ~, M# W$ ~) V$ Y2 N3 T* |
         5. #删除用户
  1.           db.removeUser('name')
复制代码
; `: O- i; u/ P% N
         6. #查看所有用户
  1.           show users
复制代码

. v  _" X* C, O+ O, o6 P
         7. #查看所有数据库
  1.           show dbs
复制代码

1 B0 }* |1 \* J/ H( \5 S
         8. #查看所有的collection
  1.           show collections
复制代码

1 |( c3 i2 X. B5 t$ Z) `
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

: F( ^" ^  \/ @  t: g
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

0 _: v: |3 l+ [" o$ R
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
( V: g5 |7 E" H* l$ {# Y
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

$ l# y0 e5 X/ m3 k
        13. #查看profiling
  1.           show profile
复制代码
+ A% r* p( s$ {- m! q
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

* j& o0 M4 r5 d% e1 u2 K, h* Y
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
. ^' A: N8 ?3 ?2 Y3 g' d  O
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

3 A! u$ `0 T7 z3 |0 Q
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码

3 a, T4 e+ _2 `; c" t
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

9 l* e# W6 l* H* p( m* X
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

5 d$ E6 m$ B+ m, }9 M5 r4 t
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

( U) i& r0 P4 Z- S
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
9 l, x; u9 K! V* f% o- v
   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()
- s" P! T. e1 {. d4 ~0 t
6.  高级查询
条件操作符 $ `' b6 v" ~. y8 e5 \3 }9 e
  1. $gt : > 9 O, ^8 b( _$ Q& V/ g$ x6 m  h5 J
  2. $lt : <
    . `: f  [  _2 I1 |" K" N
  3. $gte: >=
    ) o/ R% p4 O& L! J
  4. $lte: <= , Q0 h0 U1 h6 b+ N
  5. $ne : !=、<>
    % F) f$ ?4 v- d; @, t7 ~7 {5 [! E* c
  6. $in : in
    . W- v8 g  D* ^6 Q
  7. $nin: not in
    # K4 ^1 Z0 p4 F  S
  8. $all: all ) L2 @6 U  P8 W& M$ a  Z! M
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

# @& R" i  R0 o, D: I$ W6 L9 E7 Q1 K" A) v8 d
查询 name <> "bruce" and age >= 18 的数据
, d6 k' n0 k1 e+ ?! r
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

# a# W% @( `- E1 K8 y0 y: G# W% i3 v' Q6 @
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
( }: b0 r1 p+ a7 t+ I! Y( [: V
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
! V* x5 `! y0 t4 @2 n
& T* f$ X' T# _: X
查询 age in (20,22,24,26) 的数据
4 }) R8 t1 r7 ?9 c7 |1 n* e
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码
) j* \5 V1 f$ p
* J% w/ z3 p1 l
查询 age取模10等于0 的数据 + ?; H, L8 \' A1 L
  1. db.users.find('this.age % 10 == 0');
复制代码

8 B) b5 E$ A2 A, a; y9 r" ], x4 q或者 ' J9 G7 d4 w! i/ H" g. j
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
) m/ b' Q4 s( G2 ?' ?$ J
  y7 |, ~/ H' r! R- a5 i3 s
匹配所有
% T0 N; [7 B# R
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码

* Y0 o7 h6 N% r6 C5 {& C/ l可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } $ u0 G; E* H- k' [
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
/ T& V6 ~# R+ D3 v- G+ r- A1 c6 ~( R6 \: P; w, q4 K2 _% {: T
查询不匹配name=B*带头的记录 2 s) }' L3 o8 C0 v- \" s- l' ?* X
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

# P% _- x" n; r( o# i( X# K9 ^$ }查询 age取模10不等于0 的数据
7 b, c8 i3 a% p' ]
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

) x0 q% n$ D2 Q5 I+ F- X/ [& M/ J7 g1 j2 u8 Z* t/ c3 v- x3 |7 L
#返回部分字段
/ P- k9 T8 y) a. H; n选择返回age和_id字段(_id字段总是会被返回) $ O7 r7 `' o! b1 `$ X( u
  1. db.users.find({}, {age:1});
    - [2 G- e6 A8 ?0 |7 e
  2. db.users.find({}, {age:3}); 0 E: e. v  m; m
  3. db.users.find({}, {age:true});   K' g1 a( L4 R5 ?  N" |
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码

$ z5 F# F! h1 C/ R0为false, 非0为true   B* a5 E/ h/ o( A
* n( e! C9 J( h% a; v1 A
选择返回age、address和_id字段
+ J3 C1 K. N  c) d5 a9 ~
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

1 M9 d3 |) u- X, \' N; o$ W  e/ O7 \1 g
排除返回age、address和_id字段
1 E# h6 Y/ U3 C9 u" E! z2 J/ l( @/ V: U
  1. db.users.find({}, {age:0, address:false}); " E9 W: F3 p, o) R% [8 \0 F* Q5 @
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

- T$ w% f3 n# v7 w: T& X: ]2 O- T/ X! a% m8 ~$ `& R
数组元素个数判断
" {& e. G' N+ ~( \对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 ! ^( V3 G/ B. A/ v6 z- S0 T
匹配db.users.find({favorite_number: {$size: 3}}); ' ~5 |# S3 o- c! Q
不匹配db.users.find({favorite_number: {$size: 2}}); ' z! f) K5 X* x  f
! W9 J* Z4 l! u1 w. }
$exists判断字段是否存在
3 K) @, `) ], i查询所有存在name字段的记录 ; s: g3 k* M7 Y" G# m
  1. db.users.find({name: {$exists: true}});
复制代码
1 i; R  g; Q! T! t. S/ R
查询所有不存在phone字段的记录
$ L( l1 x) G7 `, m+ x2 ]: M
  1. db.users.find({phone: {$exists: false}});
复制代码
. {: Y! ]) }+ K* ~1 }

( F! _  L# u  j$type判断字段类型
8 a+ F% d% l4 l; ?9 a查询所有name字段是字符类型的
2 m+ O! K! w2 S0 g7 X5 l0 k
  1. db.users.find({name: {$type: 2}});
    $ s$ i" k7 j% o3 S; B4 d
复制代码
# z% G* u( U, g3 Y! D1 Z: t& |
查询所有age字段是整型的
& {% e/ H7 H, L2 D3 f$ m( h8 n& y
  1. db.users.find({age: {$type: 16}});
    - e" Q' c- V% \, T" X
复制代码
4 L0 u" o% ]) ^" L# d5 y/ V" @
对于字符字段,可以使用正则表达式
8 ^6 ~6 J9 x9 @$ @' A5 K查询以字母b或者B带头的所有记录
, K: \; G5 W$ _& R: X; V
  1. db.users.find({name: /^b.*/i});
    - O4 s4 ~( u% P  S* r. q, w
复制代码

- n  A  }* ^$ O  y% l$elemMatch(1.3.1及以上版本)
" \1 d+ _7 V  w8 \, G& S. K为数组的字段中匹配其中某个元素 3 [% M  ?; X! n

  `) Q2 [" C+ ~& s" a/ fJavascript查询和$where查询 ; r0 {* o* u$ G8 p1 P- `' R
查询 age > 18 的记录,以下查询都一样
' N; z! S$ t2 N7 S. k0 A
  1. db.users.find({age: {$gt: 18}});
    ; ?( j2 {; l* ?/ u+ M2 s! T
  2. db.users.find({$where: "this.age > 18"});
    4 U/ w8 ~9 H  E* o$ j
  3. db.users.find("this.age > 18"); 6 a- n6 b' X# D2 L
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

7 u9 ]) R1 ^1 P2 l  S3 S* r7 {' ?9 F# G0 }$ m
排序sort()
: t7 K: M& R, u- O以年龄升序asc
: M0 V1 b1 R, T; a) _
  1. db.users.find().sort({age: 1}); 1 ~* S/ A1 i2 y! N, l6 t
复制代码
8 q5 i, y, [5 x7 s
以年龄降序desc 9 e9 L$ b% S9 N2 K6 N* f* X
  1. db.users.find().sort({age: -1}); & h0 F' C: q. A9 A; T$ q" p7 C
复制代码

) U& @7 U4 h0 U' Y限制返回记录数量limit() 9 s$ x- M6 d9 R! {8 `
返回5条记录
! I: O3 N( H3 {& ~" n2 `" m1 S+ ?7 w
  1. db.users.find().limit(5);
    " p+ }2 [. j# a& m7 Q" V2 N5 R
复制代码
! Q0 o" t0 Q8 r4 Y3 m) K
返回3条记录并打印信息
9 q& y0 c  o! o# {& z* T- s
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    - U: ~0 K7 ~$ c# U& U. f
复制代码
1 j! K( e& J9 L9 W! C
结果 , q) w- N6 Q" Q& M8 g
  1. my age is 18 % e4 e/ B) }' A2 }
  2. my age is 19 5 F2 p' }+ L1 R/ ^2 c* O1 j3 }' r
  3. my age is 20
复制代码
, {; X7 w' X5 z

( ]7 A0 m9 \. G7 c# ~) W: V限制返回记录的开始点skip() ) k: J- y. C3 u9 m; t, [. g
从第3条记录开始,返回5条记录(limit 3, 5) : [8 Z1 x4 W3 g3 k. J) O$ p  l
  1. db.users.find().skip(3).limit(5); + D* D4 w- @5 m
复制代码

' H. e3 q7 H4 i查询记录条数count() ' P" P! n4 u& N7 X
db.users.find().count();
8 C5 Q8 k, H3 Y0 O2 r% Cdb.users.find({age:18}).count(); - ]( `5 w$ k3 V8 G6 w) h% Z1 I
以下返回的不是5,而是user表中所有的记录数量
8 g) i8 O) i) Q- q% K* |# a3 K8 gdb.users.find().skip(10).limit(5).count(); 0 Q% @+ g4 b( ?- Y* B; {. u) A
如果要返回限制之后的记录数量,要使用count(true)或者count(非0) & \; \8 W: n8 ]7 x: D; _; u
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

1 K5 k* ~  d( b, d; V
4 U' b- n+ p8 N; ?" [2 ^分组group()
. p- ~+ d+ p/ ?& A假设test表只有以下一条数据 ; x% w% _5 p. `/ ]5 e9 W
  1. { domain: "www.mongodb.org"
    5 K+ X* X1 N8 k
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} % S1 s* [: ~+ l# |
  3. , response_time: 0.05 4 Q* E  s" _  _/ c
  4. , http_action: "GET /display/DOCS/Aggregation" 3 o6 m2 H: B* E4 _. `+ {; s8 h) \+ ?
  5. }
复制代码

& T1 P/ l/ e( h7 J' P使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; + A( ^: Y4 m( @8 H# l( u# B3 C
  1. db.test.group(
    ! ~; p! G$ a- H( u4 g. {$ B
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} 3 v6 J2 k) o- h
  3. , key: {http_action: true}
    * Y5 m. {3 v1 k. {8 b& V
  4. , initial: {count: 0, total_time:0} 1 |2 T5 ~* A  ?' ]5 i
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 3 z4 I8 x2 j8 _" p& _5 _# x* y
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    # [4 N7 `, }8 n* r! w
  7. } ); 7 r) s" V' a/ {4 L* ?$ E9 A

  8. 8 A0 Z8 _: y' \
  9. [
    " R5 p) X! H$ O7 @2 B9 g1 ]
  10. {
    / {( R; G' x8 M7 P5 q
  11. "http_action" : "GET /display/DOCS/Aggregation",
    0 ~$ k: m, t- E$ F
  12. "count" : 1, 1 i4 m5 X8 p' Y' c7 s
  13. "total_time" : 0.05,
    " Y% J8 I5 p: G1 k& p3 t, p
  14. "avg_time" : 0.05 ( X' v- W  |0 E/ f
  15. } & O" ?5 g" q% l5 v, U  }" h" k; c
  16. ]
复制代码
  o/ b& {. {( k) V. G0 K& l$ [

3 S7 `* y0 T+ j- @$ i, v& g
- V4 v, T+ W: L) S: L: eMongoDB 高级聚合查询
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+ a% K# s9 [/ I+ f  S4 O+ t5 V( ~9 L, W
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
! h# m+ N& W# B5 P) C; N7 t9 a

% m% M! W0 o" h* h) W& O7 h! c

+ N/ m0 K) }% V
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct+ n- D1 y8 ]- ~1 M/ B* L
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
: p/ U" h6 o2 M3 ^+ H+ e! a( c
  n( g: D& D/ J' L+ r' f
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

$ F- F) I. V6 {) s/ |' L
% f( V) J  m3 d+ H
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

5 z7 h1 \6 b/ r! ?
/ {( |: c( q9 |3 b1 X
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

0 e. l& J- z9 }9 o
1 G- p8 D' m4 R; ?- V
输出如:
  1.         
    : @5 w9 k! |0 P; v3 e1 |
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

- j% T5 R% n: F4 [, @# P! _) [/ _) u: g3 s5 C4 ~, G( @8 a

& l- v( M" g) N$ r- h+ Z0 p! i
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"
    8 l8 S3 G% Q% b) B, Y) Q$ Z0 t- {4 W0 Y
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance", F5 Z' z; y! E* [+ T* W( h
  3.        xmlns:context="http://www.springframework.org/schema/context"8 Q3 Y7 {) g' g- P' `, a5 ?
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo": Y5 n$ Q3 @% w/ T5 n) Z, P
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    $ q7 L: J0 |5 M9 K
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd) Z: @8 H1 g7 O2 L) R
  7.           http://www.springframework.org/schema/context1 b: |. t; B0 X; x/ ?
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    1 b2 D' ?# S- |1 f! L
  9.           http://www.springframework.org/schema/data/mongo
    . E2 s0 x; e6 I, d  h* n9 E! j
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">) x+ l. @5 r/ V& z; R, G9 Q

  11. 0 H9 k1 J9 F* r- L
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    1 k8 I" ]0 X* k

  13. 7 }$ l6 S4 i/ O% g$ d; a! i
  14.     <!-- Default bean name is 'mongo' -->! d- C. `* C4 k1 m
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />3 z# u! U' F2 r

  16.   e6 Q+ u3 J5 W
  17.     <mongo:db-factory id="mongoDbFactory"/ v2 i6 r6 o. d5 c
  18.                   mongo-ref="mongo"- D  E$ j, Q/ W# I" `6 ]# l1 E
  19.                   dbname="mongotest" />* L( }' ]3 ~% d) Y5 ]
  20. , y! ]# ~! A; {- {3 K* Y* X
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    ' r1 P. O0 O( S+ H! J$ o, J0 K4 K
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>3 k6 h9 T# v) r6 V$ f3 y: s
  23.     </bean>! c1 ?' I9 x- \; F: k3 d
  24. </beans>
复制代码

3 r! [/ H5 j0 o! L

& f/ T! o, v* T
maxmin的测试
  1. @Test7 p0 [2 G: p4 J( w& x3 T
  2.     public void testMaxAndMinAge() throws Exception {
    $ S- X% j3 L" c3 J* D: r
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);0 x$ Y( n& }4 n1 a9 C
  4.         Person result = mongoTemplate.findOne(q, Person.class);
    . G2 v2 u$ K; ?( [
  5.         log.info(result);
    8 q3 \% Z- ?/ y1 }* C1 s
  6. ; Y' C" u6 L1 E
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);. k. X% c( J# a
  8.         result = mongoTemplate.findOne(q, Person.class);( b8 ^% i! p3 C2 B# j0 \0 v$ F
  9.         log.info(result);# l: ]+ C0 [6 S+ k& ?
  10.     }
复制代码
/ _) L& A. \# f/ J- ?- a, |# Y

) p6 p$ \. n- W9 ]3 r
distinct的测试:
  1. @Test
      [0 d6 |0 _: [8 N
  2.     public void testDistinct() throws Exception {
    * K; _- M3 [8 K% y# |2 p
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");& K. C3 E0 T( ]5 A4 U; i$ e6 }
  4.         for (Object o : result) {
    9 T. R, O+ t  F9 V8 |8 j  o% ]5 G
  5.             log.info(o);
    6 w% _! ~! E' Y
  6.         }' l7 ?& ^! D$ A0 F% s$ L) k0 z  X& B
  7. ! j$ t& ?- U. r' A# B. ?
  8.         log.info("==================================================================");" v* ^1 ~! L' x+ k  @% o7 Z
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    1 i4 o0 z0 u7 L& y
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    # }& ]5 Q$ f& ]5 q. m6 [' c
  11.         for (Object o : result) {
    : v& @7 q& P. q) j2 z
  12.             log.info(o);) Z5 q! E3 Q; O% w
  13.         }0 D2 i! b3 ^2 n: ?

  14. - a& P( W9 |$ p; e
  15.         log.info("==================================================================");
    $ o7 E! b/ N# j1 Q, o
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");5 e/ U  F# ~5 [1 V3 l+ P2 h+ J
  17.         for (Object o : result) {1 ]. [6 U1 S3 C7 x2 x8 W
  18.             log.info(o);
    2 m( b0 f8 b6 T: @
  19.         }
    4 d9 g5 O6 r) E) p
  20.     }
复制代码
  A5 \- M( n3 Y
9 U! r; i) }% h; Y4 Z5 n
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567# U/ S- q, N1 F; p+ O% A# D1 a1 I
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678, z, \0 C3 m8 n6 D5 m
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789* f) X' H4 `- [' _
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
    % A- |- R6 W  D0 p/ u& {
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni& D/ @# n% n, N9 X
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    % R9 v/ L+ {7 v" {
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456: N# P6 p& m4 E8 |; e4 j
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    ; R% a- h7 i7 Q- w3 @
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567# a$ \, w6 \8 J" G/ i$ Q2 S
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    + z7 d& N* f1 T, N, J9 Y8 `
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 4567891 _6 H! F0 D$ U4 c: x; Y
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    9 p" k" ~; l5 b; R/ n% y2 F
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================3 k7 D# d3 k% E+ J
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa) q5 f, t/ x* G  d- N# p( G7 ~
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb$ S  k4 ?1 I( ?! A6 e7 j
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc7 d, V& r  ~8 R/ v2 H
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www) g' g" C  ~) [0 N5 c7 Q
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx. y# w4 S/ g8 t$ G
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy& s! k2 n7 ?1 p- g( v  ?: g
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    4 ]( O" ^, g0 i0 G( X# ]  J, v7 V
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr% o1 k* v" g* |( {1 G$ m0 o
  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
复制代码
2 a5 [% U$ w  Q9 M9 h6 R

( q8 Y, Q* j8 x* `
这里我要特别说明一下, 当使用了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等信息。

: f6 E3 p4 Z5 X6 u+ ?8 s* W" e& b0 ^1 u8 G6 F. j* q

% c/ u( W3 T* O) t+ K; x: j3 ?
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-6-19 22:40 , Processed in 0.079101 second(s), 24 queries .

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