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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |正序浏览 |阅读模式
版本一:. ]4 q" s( r  H2 `

* ~. n$ W3 k  h) N3 j4 l; N1 ) . 大于,小于,大于或等于,小于或等于0 X/ R! v# `, r  o

! n  i6 t+ e8 c) `8 m* K  z$gt:大于
/ _$ f/ q0 x7 q' R$lt:小于
1 M7 x& ?! h3 V( ~6 p# g6 V  r8 W$gte:大于或等于1 R$ u0 W& v& B
$lte:小于或等于1 P5 e3 m( [# {3 a0 k4 h" `, A
& a6 K- A4 w' W6 E
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value/ u6 t( \  h" T, j  w. F$ o
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    4 a( c1 ~. r/ b7 v- q
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    6 k1 Z7 d( {. N/ r: V( P8 |
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
$ q/ h2 j1 b3 W9 w; L9 H
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});, E  b, H# C6 L! {" a, |$ B5 {
  2. db.things.find({j : {$gte: 4}});
复制代码

$ C1 P- a( r( v- B! G0 W" k
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

# C; w1 @/ q  Z! G8 f$ \6 B2 Y8 p/ J- j5 n3 S+ p$ L  f

5 Z+ w/ I1 n5 h1 \4 n# A
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
- ?  r, z, L" S  b8 ^
3) in 和 not in ($in $nin), R( x9 P6 I  k; D& H7 }# m: P

3 D8 n* j" ~) c& J; ~: |+ f语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
& g( A  z% G4 o
例子:
  1. db.things.find({j:{$in: [2,4,6]}});% x7 v5 _4 o5 O& V# y
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

( @, _% s' Z3 W* r

1 G% w0 ^7 A+ B. a, j/ y4) 取模运算$mod! _& C* ^. s& D$ D2 m6 t

  w" W4 {% f% v. Q7 v* C( r如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
7 t6 l1 R5 D3 e- Z+ U1 Y
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
! `! [7 W) |" n( E! _

* }4 V' p6 p% L) V+ w; Y0 p/ Y4 F0 b5)  $all9 l& v9 i% p, a6 d
; B& w6 J/ H( H. y: s9 A+ o
$all和$in类似,但是他需要匹配条件内所有的值:* D8 I  N& ~! Q+ [' E
0 @2 E% h3 f7 k
如有一个对象:; `& {' i& y  F
  1. { a: [ 1, 2, 3 ] }
复制代码
# w2 G( m% M% a% J/ {: e& i
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

$ x, x1 C' g. f# {. a( |/ v9 a
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

* W; X: B0 O; Y+ X; t) [
, [  [& p7 W6 X: p
6)  $size; l' e5 \* @8 |- m
+ d# d' N& d( S; z4 {! [- W2 H4 H" O
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:# H; I! I4 W1 S5 l: m# u% v1 H0 J
' k3 {: E! |, v0 r
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
) B$ A$ p% n0 _
官网上说不能用来匹配一个范围内的元素,如果想找$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.

. r1 i' m% B6 ^0 o2 Z6 c2 x
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回4 ~- ]; z" T' O+ n+ k# B8 i4 r9 ~0 Y
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

- q$ z: Y7 h- S% s/ Z7 {
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    7 C0 H2 w5 _! m- i3 L  K% F
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
% s2 V7 N+ x/ i# L
9)正则表达式
! R; y- b% I% I  U! H( w: R( \- t5 W7 M( H: Z7 u9 O! O" u& N4 e
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

$ z2 b: Y7 L# `
10)  查询数据内的值
2 L6 G. w) K' D# x4 @; D9 l' L9 m- V, [- b# g
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

7 {, S5 C/ X7 ]% r3 d" v8 Z
11) $elemMatch& n# X5 u$ }. P' W9 p3 e' {" T# |
! C* l! l% b9 O5 J* ^
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) ! k$ C* T+ t  Q: ~2 z& V
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    5 Y- p9 W0 ~! `
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]' [+ b4 ?3 B  V5 s- `! d, @0 Y
  4. }
复制代码

! K6 U6 }1 b, {( c$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )& Y1 K/ K5 h9 ?+ @( W: w
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
2 x  e/ g' N2 i$ F- F2 D; _! U* ~& v% F' L( p" r; T  E
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
" _! r+ T1 J9 m7 ~- x+ @; }6 t
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
1 B) v6 T* E3 u/ W
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
2 @/ l/ v/ B5 F% [, v& ]1 c
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
0 `' i8 l1 ]7 }  Z
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
3 L" j+ Y4 W0 ^! L
是不能匹配的,因为mongodb对于子对象,他是精确匹配。

& U! J. F$ o1 V  [
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );
    / ^' J( b/ b; Z% w$ [; ~
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

3 P) k- V; P) k
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
2 @1 i, T0 f4 Q5 n9 h4 O4 N) m5 ^2 y1 ]
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:3 M6 ?2 d! {$ W  s" Y
2 E5 W, N* ]8 |$ Q% Q" B; R
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions- b1 _6 D) ?; q/ @9 |+ F0 @, L& I2 _
- }" d* K$ x; v% E0 |8 g6 O
版本二:
7 e- J8 m$ [) R; s
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

3 Q( q' U, ^# m/ V! v
  1. use admin
复制代码

" f9 a+ F7 ]: m8 s
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码

1 t* |5 S! ]  _' w% R; g
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
' a4 q# G  x2 E2 L2 L& w6 C
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
3 q" o6 t6 e: s) a- o; A
         5. #删除用户
  1.           db.removeUser('name')
复制代码

4 _# N0 _1 r2 Y
         6. #查看所有用户
  1.           show users
复制代码
# W9 N$ W% A* O. v" E" \: v
         7. #查看所有数据库
  1.           show dbs
复制代码

1 T2 u  O- B5 J2 w' R2 R0 `
         8. #查看所有的collection
  1.           show collections
复制代码

0 B2 N$ J' R1 q5 }+ _
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

$ M% g6 T$ U( F# r
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
5 |4 J( V0 k" c5 w* c. J/ o& |* a" W
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

1 `5 Q3 p1 J: E/ I6 Y1 g* B$ I
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

+ p* l5 i2 _1 {. P( W: `: N7 @. S7 j+ H( P
        13. #查看profiling
  1.           show profile
复制代码
  K+ v( L$ [( o; O/ g- V
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
2 u  c, ~) l+ [) W
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
- E' H0 j( E& T+ E/ J7 g/ P
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
# q1 ]  O1 T8 _  O
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
4 p0 ~: l3 A' ]" [" c& {
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
9 ?/ V8 G  X6 B% b# ^) A9 I3 `
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
, Q4 C, g" D* A8 J
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

, v! I: P+ N& R  ~# \
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
5 W$ k% J, N6 L
   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()

4 c$ J/ g# [, E" N& u
6.  高级查询
条件操作符 4 R  h' m$ z) Q5 p7 X- i
  1. $gt : >
    0 y1 b6 d, B" Z9 w4 i3 L
  2. $lt : < ; R, q" v0 t/ \, c
  3. $gte: >= # C. S% [$ S. q! @( b
  4. $lte: <= & d" h; J$ f' Q9 k
  5. $ne : !=、<>
    6 h( w6 s+ E+ s2 s
  6. $in : in & N' ^- r" O6 l' x, z
  7. $nin: not in   ]% B8 Y  _6 O2 w2 [9 O5 R, I
  8. $all: all
    ' `' {8 W$ T$ ?: ^3 W
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

% R; a$ R, T$ }, x* j* s  f
/ S% Q2 P# D" T1 W) i查询 name <> "bruce" and age >= 18 的数据
# D( D# Y% o6 w4 o" f% D% l
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
; |. u0 S5 ~0 l
+ ^, C7 D1 X( K4 D  g3 g  r
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
6 |. U) G, K3 ~' R6 [4 X
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

9 R" t3 Z! Y; @6 O& \8 T* O
& k: M6 `0 e) O- w* V. b( J查询 age in (20,22,24,26) 的数据
. U7 d# @/ \3 H7 a/ b% ]) x
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码
8 ]; y# }8 J5 c& ?
# N! C) }4 f2 _! x( k
查询 age取模10等于0 的数据 2 [6 C/ m) Q" Z5 L) N
  1. db.users.find('this.age % 10 == 0');
复制代码
8 F6 Q' W9 `$ C& C
或者
8 ]- M8 j  G7 a: y
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
* V9 a  u" ^5 Q% ?
; F1 `$ v. p" ^1 n1 l
匹配所有
+ }7 Y7 n* g2 z2 a  G
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
1 C8 p8 Q. N8 j6 S7 D1 P
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
, V+ G& m+ m$ Y5 P4 A可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
' [7 t5 j0 U; D7 M  E$ R; c
  _+ E6 X5 A  F0 _0 U查询不匹配name=B*带头的记录 + f" X- w2 M! j  @+ r
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

, v4 j: P; K, }查询 age取模10不等于0 的数据
4 L' `% K4 o2 ?
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
6 T5 }* {- Q2 ^' e8 ]; ]5 R

1 K+ q& ]0 C! f#返回部分字段 4 Y2 _1 E* q* U* G. Z
选择返回age和_id字段(_id字段总是会被返回)
% C4 Q9 E0 V- z# P" Z# \6 z! }# @1 w5 _
  1. db.users.find({}, {age:1}); 9 g) F/ W* o- P$ Q+ I. q4 q# f
  2. db.users.find({}, {age:3}); " x1 o" _4 y% l
  3. db.users.find({}, {age:true});
    ) ~! h, ~) e1 e$ H' Q6 _$ G
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码

7 z% h8 }& r! q/ z3 U$ G5 z' _0为false, 非0为true . D: V# s) a6 `+ z# w+ b

# G/ U- O* L6 e! y  l5 D+ e$ S选择返回age、address和_id字段 ' Z! @: }0 l, A+ O
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

$ v- W2 F! b7 Q& w; X& x9 h% h$ a* C8 E! `
排除返回age、address和_id字段 ! P7 N% m* a7 h* w5 {1 h; K
  1. db.users.find({}, {age:0, address:false}); 0 V) e# c8 j- m3 n, W/ n
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
! C. z* Y$ M$ i4 |2 y5 R
1 B1 V) u3 p/ _$ t+ p
数组元素个数判断
9 `) K+ Z4 w; k" R- r对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 8 ?# d* t$ K& E% g/ i: Y" A
匹配db.users.find({favorite_number: {$size: 3}});
# y1 S" D+ j# _3 H不匹配db.users.find({favorite_number: {$size: 2}});
) p* p  c) F5 [6 g9 `( _0 i' \- K1 V# ?% A+ }' u% t
$exists判断字段是否存在 9 O6 t( Y5 Q  d9 I* h1 E0 q
查询所有存在name字段的记录 : P! a% M" M. |% J6 u
  1. db.users.find({name: {$exists: true}});
复制代码
8 W  t& w8 p! N# C7 n- t# [1 P+ L
查询所有不存在phone字段的记录 . L* k. v, y* @- X9 ^, @
  1. db.users.find({phone: {$exists: false}});
复制代码
5 o2 v9 m& x" @0 R" H

8 f/ u2 f7 Z2 a$type判断字段类型 ( X  S, h7 A+ d( P2 x# O$ ~: M
查询所有name字段是字符类型的
* O, |5 }6 N- d  W7 B
  1. db.users.find({name: {$type: 2}});
    ) v' v" Y8 L; N0 W8 I$ `% u
复制代码

; k7 T% [. |3 B' P查询所有age字段是整型的 : X. K( J$ b& Y; V' z+ U
  1. db.users.find({age: {$type: 16}});
    2 d$ W" ~1 J0 n
复制代码
. U  O& G4 C% Y6 J( ]
对于字符字段,可以使用正则表达式
- ^# l* X1 p1 [查询以字母b或者B带头的所有记录
  r2 T' f( _9 t" T: j0 M
  1. db.users.find({name: /^b.*/i});
    ' ~2 K' x" j1 ~- B% l8 ?+ J0 r2 J, b
复制代码
! [' P* d; p% f5 Y& r0 Z  g
$elemMatch(1.3.1及以上版本)
5 ~& f$ s) i: U" ]0 ^" _7 H/ `为数组的字段中匹配其中某个元素 . {$ Y) {  Y( Y4 {" W5 |) u9 s

0 n6 O- E) V% j; h* d: d0 ^Javascript查询和$where查询
0 t' ?# f0 K, e* _查询 age > 18 的记录,以下查询都一样
  F* F5 J" A' \! U+ p& t1 {  ~
  1. db.users.find({age: {$gt: 18}});
    / c  b. S) U3 ^& m
  2. db.users.find({$where: "this.age > 18"});
    0 B" P1 N4 c  f+ ]/ F" Y6 @% h
  3. db.users.find("this.age > 18"); 6 n# U, W8 J. d* K" y6 T
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
3 w7 x6 ~( H/ x+ W  s% {
3 h# P" E6 m# B% X+ }* T/ a
排序sort()
1 D& h; U+ A& q& |% \以年龄升序asc
* G/ v8 S; N) \0 K
  1. db.users.find().sort({age: 1});
    + x; f* L# C" a% P% }% ]
复制代码

. Y& a- L+ ?1 h1 b. J以年龄降序desc
2 C7 L7 c( [$ c& q+ _
  1. db.users.find().sort({age: -1}); 1 @# Z. ?3 Q8 V
复制代码
. u4 U) Z% h* B* }' b; i
限制返回记录数量limit()
& j0 g- I6 j8 U# W返回5条记录 ( B6 l' l% b2 w% ^& B: j: f
  1. db.users.find().limit(5);
    6 {% P: E' Q9 z! p, `
复制代码

2 N' R; W9 i  J) A1 _- s6 A返回3条记录并打印信息 ; L/ b; D) V' G2 U* I! k0 g3 s) _6 f
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); 4 }) G8 i2 a" q! R
复制代码

1 e) u& q, V6 _$ S结果
1 K7 p" A2 F5 m& N
  1. my age is 18 $ C7 K# S0 c+ u4 E& G& W
  2. my age is 19
    ' u* c/ J% I' k4 M/ X' q# g
  3. my age is 20
复制代码
7 L2 }2 |/ `2 u
* O9 l* C% R$ O0 T" B* S+ C
限制返回记录的开始点skip() ) c; I% B1 l2 r9 k, m
从第3条记录开始,返回5条记录(limit 3, 5)
5 ]( ]1 z& V" b0 |5 {; S' R
  1. db.users.find().skip(3).limit(5);
    & F9 e# N6 Q; Z+ q' t/ I
复制代码

! s+ l4 o- ~8 D$ x查询记录条数count() " W, o/ _4 B/ _0 g( O' d
db.users.find().count();
, e7 W7 Y8 G3 P! U8 Q. X1 Fdb.users.find({age:18}).count(); 2 e" L; r, s3 K
以下返回的不是5,而是user表中所有的记录数量
! S- D7 T% _. i* e, z0 e0 Z3 gdb.users.find().skip(10).limit(5).count();
* n; s2 [, m# d0 h如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 8 J0 J" Z; T9 o! t$ l, K* @
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

  r' @; K% E8 n& u6 C- |& Z
! W, t2 ^: t. O分组group() . c! D# g* s9 @. }7 O- b( E" i. ]
假设test表只有以下一条数据 / ~0 w4 m  I) n' z- ]$ |& R
  1. { domain: "www.mongodb.org" 7 z& U0 R- T2 X8 e
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} ' Y/ a" ~8 N9 w4 Y8 o2 k+ ?' H
  3. , response_time: 0.05 " ^% \' [! H# ?) f# O& ^
  4. , http_action: "GET /display/DOCS/Aggregation"
    & o5 o7 }* A2 k! y, `
  5. }
复制代码
4 p* ?9 F; e1 b: T( K& W
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; " ?5 ?! q. M1 f
  1. db.test.group(
    " @' B+ o# Y% K4 G3 p7 b3 h
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    8 s/ z* _# h! J" C- i
  3. , key: {http_action: true} * L, D7 g- w. I
  4. , initial: {count: 0, total_time:0} 5 F5 j% b& g9 M
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } , z4 v! D9 C5 o
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } 3 p. N( C: T9 Q, K. @  y
  7. } ); / ?2 S# Q" ?0 ]8 R! \( u
  8. 7 I7 v% A1 c, x1 o* C$ C
  9. [
    - K4 o9 H8 G; B
  10. {
    . j# z  M. G# N. [
  11. "http_action" : "GET /display/DOCS/Aggregation",
    2 x9 `- Z/ q" Y- t0 ~
  12. "count" : 1, 8 L' Y, g0 x  g3 n; N) ^
  13. "total_time" : 0.05, - R, L) j) `2 h- H+ ]7 F5 s0 U
  14. "avg_time" : 0.05
    9 N0 @) K" P: T) I
  15. } - H* {1 {- k% F7 y
  16. ]
复制代码

  m0 [" l3 w/ F( C% s* u! c, F9 Y7 s* O  t8 M1 H/ ?$ p; N

2 K2 d, ^- |4 {( ^MongoDB 高级聚合查询
MongoDB版本为:2.0.8
系统为:64位Ubuntu 12.04
先给他家看一下我的表结构[Oh sorry, Mongo叫集合]
如你所见,我尽量的模拟现实生活中的场景。这是一个人的实体,他有基本的manId, manName, 有朋友[myFriends],有喜欢的水果[fruits],而且每种水果都有喜欢的权重。
很不好的是你还看见了有个“_class”字段? 因为我是Java开发者, 我还喜欢用Spring,因此我选用了Spring Data Mongo的类库[也算是框架吧,但是我不这么觉得]。
现在有很多人Spring见的腻了也开始烦了。是的,Spring野心很大,他几乎想要垄断Java方面的任何事情。没办法我从使用Spring后就离不开他,以至于其他框架基本上都不用学。我学了Spring的很多,诸如:Spring Security/Spring Integration/Spring Batch等。。。不发明轮子的他已经提供了编程里的很多场景,我利用那些场景解决了工作中的很多问题,也使我的工作变得很高效。从而我又时间学到它更多。Spring Data Mongo封装了mongodb java driver,提供了和SpringJDBC/Template一致编程风格的MongoTemplate。
不说废话了,我们直接来MongoDB吧。
  • Max 和Min
    + Z$ m5 F+ n  H5 R* T9 `0 h
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

: w3 f6 h' X8 j+ P( Q7 R! H
# Y. @. y) X( C8 f5 C6 `. s

/ |4 L" Z' l6 e9 [
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct4 ]$ }- @  X. j3 L1 q: k0 [
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
( V- e; J) H$ ^9 G

6 X, O& }9 U- X, p! M
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
6 C1 M7 I: v" m" \( X; N% n9 z! [

$ x# L5 a( p  \; E! p) ?
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
+ p. ~, L* G- q# T! a) @
( r2 L9 C) F  Q  v4 c" [! }& L. I  }
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

. r, H; d. j" n2 c4 @+ J0 y. B6 L
输出如:
  1.         
      a1 t1 N. ^: D
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

0 C5 k/ ]" j" c7 T3 E) N5 j; ]. C( E+ I- p( j# F

4 |' H" g% n! W2 \0 u1 u
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"/ u; T8 f7 `. Z8 V
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    % ?! R) j9 ^/ _' O% k
  3.        xmlns:context="http://www.springframework.org/schema/context"
    ; ^7 I1 X0 e# W: j  p- |- v9 K
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    6 O7 s& Z# D0 \1 ?
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    + v+ \% L" ^- o* O
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    9 O2 h, q; E1 V1 M' a* c
  7.           http://www.springframework.org/schema/context$ c1 @( a, y3 I2 _4 l/ @/ e
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd$ V0 J$ f0 G" R' K
  9.           http://www.springframework.org/schema/data/mongo2 ]: A7 {9 z* @' T
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">$ x& L. R! b) @1 P' u( S

  11. 2 w% }( W* k2 j1 b8 }* o; E5 [8 v
  12.     <context:property-placeholder location="classpath:mongo.properties" />0 `) F7 P- x2 v

  13. & j" e& X5 W5 B& h' s& S
  14.     <!-- Default bean name is 'mongo' -->& C$ H+ ^3 ^7 k8 f- I6 \0 p
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />( _! |0 e$ q/ |( Z: t3 |. v
  16. ! L6 x+ b# O4 K6 c- C8 h
  17.     <mongo:db-factory id="mongoDbFactory". s4 H: J8 e  y0 j! t3 w& ^
  18.                   mongo-ref="mongo"7 m; b' H( O0 X3 y7 T, `
  19.                   dbname="mongotest" />& V7 K! x( U2 h# i* u) |/ v
  20. $ |$ Q, e, G; a" m2 ^- w
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    " Q2 p! B8 `+ |* {' a
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>8 s1 [6 I% {( E- m, l- Q) E9 @
  23.     </bean>* F# U; v" f* `) _% D. X* ]
  24. </beans>
复制代码

0 B9 `, h1 ~2 k* U: b, g& j3 e  L

( B0 X: [* v& u" e3 B! [2 f+ u
maxmin的测试
  1. @Test
    7 |, G9 o& D) Z' [
  2.     public void testMaxAndMinAge() throws Exception {2 B3 ]$ Z8 E# N0 v( [" q
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);3 o5 L6 |8 m' Q0 ]
  4.         Person result = mongoTemplate.findOne(q, Person.class);% q+ z' T7 L/ J
  5.         log.info(result);7 S/ O) C7 B' R
  6. - t) T# ?1 d: g: t8 [
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);4 o5 M6 d; s8 n6 [' Z
  8.         result = mongoTemplate.findOne(q, Person.class);
    - R& ]1 v; H6 ^4 y  _) ]6 W
  9.         log.info(result);
    ; j# W# P- F% E5 l
  10.     }
复制代码
% Y4 Y5 C" R5 J  G5 ^* r3 A3 @
4 p0 Y2 ~4 X; S7 {  U) b# P
distinct的测试:
  1. @Test
    ( N. e6 K" k, V  K4 l" [; s
  2.     public void testDistinct() throws Exception {
    + ]* c% a4 Z) a, b! g/ X
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    ) t( z/ f) @- Q& ^: U: |) |
  4.         for (Object o : result) {- |+ a: a0 V: u9 R8 }/ A) ~8 {# a
  5.             log.info(o);" Y# {2 Y1 K$ p1 K
  6.         }! w, R8 ^  p8 Y  S/ M
  7. 4 j3 H: K4 H7 O
  8.         log.info("==================================================================");* b1 l2 o: B% c# f% L; d+ D
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    ' m" \* ], t: `0 l5 v6 `
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    # ~3 e6 g9 W/ g  N4 d" N
  11.         for (Object o : result) {
    ( g8 l3 ^0 [* f0 b
  12.             log.info(o);2 d$ y" ~3 E: X5 l
  13.         }0 @  E) P2 r5 B, K( r; {  L
  14. 6 A) C4 E% W$ z& i2 @4 k$ g  y
  15.         log.info("==================================================================");
    * m* U. f% ]# F2 X
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");* h& R- b- E- @8 C$ q2 c1 ^/ H6 |# \
  17.         for (Object o : result) {
    / B' c0 H5 P5 J
  18.             log.info(o);
    9 A. y8 y2 G) t# L$ i+ Z
  19.         }
    4 m0 s, n% L$ g
  20.     }
复制代码
% Z: c: J- m: ~* I

! W* s9 j* A. G6 g! D; c" t7 J7 @
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    8 {6 g* {6 n3 ~
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678% P4 ?5 K1 A1 t, z& u
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789- I" g  d* ~$ F7 S0 t7 m
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654! H/ w5 ^7 K1 q/ n3 @* \0 R
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni$ k, p1 D: j: ~
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    ! x; w+ Z' i4 s! p4 w* H* u
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 1234568 T% L$ R6 `5 [" ~) w: x
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================& Q/ S- a* s: h: l
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567% i, o; l9 T) ^2 B& S# w
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    $ ^7 i# [1 @; r
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789  U& R: P) e$ |" H) y
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
      b. M- B! C2 C
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    : G3 Q" }2 M# i& H& u
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    & H6 L2 }7 q- V; V0 h7 H( ?7 h
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb# d2 E, K1 H$ S* L: S# e" P3 B; e
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc: y# g4 I/ z% s) z; O
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    ' A! h0 B+ @; h+ d9 A: l" K6 T/ ]
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx9 p* v+ C, c9 i2 j9 S+ m1 i
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    ( I  ?( f6 t- L1 v8 c
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    5 Q% r5 m9 u* I6 [) }! s
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    3 D) v' q6 R7 E4 r) j4 [
  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
复制代码

# ~+ E7 M) p0 u& p2 w6 L5 M$ S/ o, V
这里我要特别说明一下, 当使用了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 r2 m. t" f0 V0 V! c7 [
# `" l: l0 e% z9 G+ d( w* F2 w0 e. i5 F& N- g
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-9-21 05:18 , Processed in 0.071110 second(s), 23 queries .

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