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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |正序浏览 |阅读模式
版本一:
* r4 p# |% x2 l/ c& \
) e, h5 W! c3 u$ U6 o1 ) . 大于,小于,大于或等于,小于或等于
3 D# a. \' I( ?5 q3 \, s  n, c" u! D5 X* ^
$gt:大于% W" T6 L' d2 u6 H0 ]* d
$lt:小于8 o6 K# C! q6 s
$gte:大于或等于
: g9 h3 h0 S9 |4 ~: H, e- p$lte:小于或等于" G( n! T# n: w  r
# Q0 n# [, T9 J" T' x
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value- h; x" L" I) A; L% i2 E
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value4 A$ K; A; [. {# S; Y) w6 n
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    & m! m9 |9 z" _- Z+ V# K: b; m
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
1 Z2 ^% W/ b* S+ Z8 V1 W; u+ J
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    + k( n7 ]% ^% K
  2. db.things.find({j : {$gte: 4}});
复制代码
/ Y( _- s  J7 J
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

7 e1 T! z: e' M5 S$ w8 M' k7 }! n8 U+ x2 p& q- z, \  {% I
; y4 l5 U: d& T6 J, c2 _" V4 C, z
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
9 g  e7 W& {" A1 K1 T1 ^
3) in 和 not in ($in $nin)
  [4 c: ?' {; I$ a+ b# t9 \% S4 x. j* r. [# e6 U3 ?" R0 u+ i
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

$ T' i. M3 n/ K. x0 Y
例子:
  1. db.things.find({j:{$in: [2,4,6]}});' }* u- ~- ^- y# [% t4 A
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
  a2 L1 P! M' j7 G& |- R3 Y

0 t% w, J$ `" O* t0 Z2 W1 _, s4) 取模运算$mod7 d& n9 M' O; A5 B$ w5 ~" k: U( q4 t

2 i, ^8 H$ l7 {& t# `如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

$ D& I( n/ o3 p) X1 a
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

! {" y* A# U& k( A4 W  Q. I
8 Y9 J4 b# \/ F9 N) C* K- J6 Y
5)  $all! S0 q5 d, [0 u0 C' Z" y3 r

. H% D! _3 W4 H" D$all和$in类似,但是他需要匹配条件内所有的值:; K/ r: h/ T1 r2 d
7 U( b* F; [; c0 p; i4 ]: M
如有一个对象:
) |6 h( R2 P& N8 x3 c) g  S
  1. { a: [ 1, 2, 3 ] }
复制代码
5 G! V( ^/ u4 i+ N% Y/ ?' n
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

4 s$ G2 O2 k1 {" J4 T5 M4 B' L
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

# [2 o4 u  v9 G  ^) \: R
1 n5 j, \+ W. e5 ?/ b2 Y
6)  $size
2 j( Z' w( O( W* b  j1 `4 F# O- ^; w( O/ y/ Q
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
8 p+ b) O* \5 K7 F7 e
  B0 f# C& c  b" j# k下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

2 v  \! V! b; k! A* N& J
官网上说不能用来匹配一个范围内的元素,如果想找$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+ R/ w8 A# A+ k5 X3 ]" o
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    4 o, _7 D9 @2 O: @% }0 @+ ^4 c3 H
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
; a+ K+ z( K9 h
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    4 o# w- W& p% g  P6 _
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
: l' [3 _2 {, C6 W  V7 E1 [% H
9)正则表达式* o6 ~  G4 L* U$ P# X7 ^
, Y  F  p9 Q" {/ D! x
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

1 W7 {2 e% R7 Z: z9 [
10)  查询数据内的值
! R7 U$ S/ D6 |
$ V$ R. V9 B6 L下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
$ A2 z7 j# A6 ^0 s/ I6 f; t* l7 q
11) $elemMatch
+ q- @$ X, R1 c" M; y9 ~7 }, k
0 l) E$ m: `! I2 x6 A* P! p% o如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) + j* D8 [. q2 |0 w2 ^
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  - a* a! Y2 ]0 H3 y8 c# v
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]! G$ `$ w) }( v! U0 P- y
  4. }
复制代码
' w' H( @7 }1 [9 v
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
7 P1 R1 q: [, ], F4 _! ^: b
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 0 u3 q( p1 X2 K6 X/ r- {
& x: s0 Z% i/ s
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
! K! y6 h5 s; p
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
' W. l) _" m7 A: q: E( d
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

  F1 l$ E8 [& m
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

7 u: |1 ?# E3 y& L6 _
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
1 A. n  X2 r+ L1 ~7 e  U+ F
是不能匹配的,因为mongodb对于子对象,他是精确匹配。

6 c0 V3 J- L& l2 E, U" I/ D2 W( ]
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );5 `- V  y" H$ R! p5 y
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
% A( n  r: Q2 O+ [, n) ?
mongodb还有很多函数可以用,如排序,统计等,请参考原文。  X4 X1 v  L, }- v( {# N+ w( t
0 q: ~- V: `% f2 U. g
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:8 M: V4 f9 S( P- p5 \8 b1 @5 Y  X
7 m8 d3 U7 w8 g3 M5 l( j# w3 L
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
( O& T+ H2 S5 J5 t  Z: ~
8 p/ p6 h7 e  m7 i2 d$ ]版本二:
- h& R, R0 R; R# `. [
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
9 W: o# U1 q( N; g, K
  1. use admin
复制代码

4 ]1 l, H* Z- F. U9 U- \& [
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
# m8 J9 `9 s4 M- `  I8 X
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
" T# i3 g& d+ T7 p2 x
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

0 c% j& @0 `- Z$ |4 _/ G7 d
         5. #删除用户
  1.           db.removeUser('name')
复制代码

% u: e& D- h. c! v% u! n* M
         6. #查看所有用户
  1.           show users
复制代码

  x  b5 {" Q$ L3 H; W
         7. #查看所有数据库
  1.           show dbs
复制代码

+ a8 \" i* e0 G/ ?; j- ^4 q
         8. #查看所有的collection
  1.           show collections
复制代码

+ ?  r; n/ z9 m/ A; X0 I
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
& C% x+ y* U& Q7 x+ g: |
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

: _- n, J& q6 D; u
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
7 |  T% w3 t! j5 Z( t
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

+ v7 W! K" j8 H' V: C
        13. #查看profiling
  1.           show profile
复制代码
  w- r7 A: E' a; k+ F
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

8 D  G" ^) |+ W
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

$ {# H1 k+ Q- B* f! n. t. A
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
+ h  n4 S, }% _! R# A4 C
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
3 d" p# D& j6 A; ?
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
0 |# _, v2 Q+ [- e' O: ^3 k
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
+ V& T  ^7 h& N8 a7 F9 q9 s
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

. g3 d1 L4 U: J  w- n
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

7 F* j3 u" S4 W/ H% H1 I
   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()
3 r" {. `, h2 a+ C; ^7 \  D
6.  高级查询
条件操作符 2 j+ W* Q2 }# ?. H- G. G: Z/ r. j( b/ k
  1. $gt : >
    7 f1 U# \0 D# H6 J# u
  2. $lt : <
    # |6 k6 ]+ s: P7 a  y  c# K4 _6 o
  3. $gte: >= 1 D% h; y4 U5 @! N
  4. $lte: <=
    . q2 C. d1 _* m, F- Y9 T
  5. $ne : !=、<> ) t: x# S5 Z* g8 k
  6. $in : in
    7 a& F+ k: Z! C- F5 v
  7. $nin: not in
    6 u, i& h& j- c+ G
  8. $all: all
    2 A1 S6 R3 i8 n0 x
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

" B+ {, |: H* Q$ R! ^; ?; P+ w$ |( X% p( n" e" H, n# c
查询 name <> "bruce" and age >= 18 的数据
1 H) d$ c: s* b& i8 ?
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

( R4 G/ ], u8 m. c; e; w6 Y) X6 [
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
) c4 J" x  B* I/ l: F
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
/ c+ v- v/ {" a/ Y  M
8 S2 s% F, J0 D& R3 {
查询 age in (20,22,24,26) 的数据 7 `) t7 Q8 c5 P1 i; K
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

  g8 h7 m7 _; Q7 p% m4 Z1 {( O
: m2 i% M+ G$ `: m查询 age取模10等于0 的数据
9 [; @5 n6 b- t3 z% J  U3 g: A
  1. db.users.find('this.age % 10 == 0');
复制代码
/ E  t- @7 T- g5 M/ W
或者 % b0 D  W4 O5 |
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

0 {5 w  d# U, A2 c
; H$ U1 x8 Q! ~0 j* \  I' y0 H5 f匹配所有
9 ~1 R+ L! E+ s) f$ ]* T. v
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码

; }; n/ c! r: y4 B9 D$ M可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } & }7 U, Z0 G) i& I! }2 E& P: ^
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
6 a! W7 V  I8 H" R& O5 _$ ^. w
* F# \% X/ f9 t0 Q5 E  K查询不匹配name=B*带头的记录 + i1 [2 g  z5 v
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

4 E& z0 p6 m" ^. S0 z查询 age取模10不等于0 的数据
; O+ o: j3 D& m
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
. W+ P0 H0 d  S  r4 [" @5 j
: p4 T6 @5 e/ b/ u0 A
#返回部分字段
* I# X3 e/ |; u选择返回age和_id字段(_id字段总是会被返回) 5 P! q4 ^1 t3 ^3 K1 B
  1. db.users.find({}, {age:1}); , Y0 u2 h1 u$ q! L" A& T
  2. db.users.find({}, {age:3}); 4 [- Q. P. d! ~6 }  S: ]% S) T2 |
  3. db.users.find({}, {age:true}); 2 ^. {( O! g: {8 A6 U# w0 P" P* u6 k
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
, q: y* Y" V, i) U
0为false, 非0为true ! Z! O' w( p$ C  _& j
7 I( S" v0 ~7 l3 c) r& E- Z
选择返回age、address和_id字段   K8 T2 E  j- p+ B  J
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
- J4 @1 e2 v* l

& N! N6 W) Q2 q, y5 H) z排除返回age、address和_id字段 + Q' D1 l: v9 d9 A9 ~1 a- L
  1. db.users.find({}, {age:0, address:false});
    ( ?6 ^" B: C: z
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
7 ^( W3 ]  w' T- R( h
7 p, N: i5 l: T; ]* S& e
数组元素个数判断 5 Z: a. U) J& O  H
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 / R5 g: B0 f' h" G, ~* S9 o
匹配db.users.find({favorite_number: {$size: 3}});
, D1 ]" @" @$ M! ^4 ~不匹配db.users.find({favorite_number: {$size: 2}});
  Z) [& E* r; U1 r( M3 Y! r
# u# c+ `+ G1 E! a2 G$exists判断字段是否存在 - h* B' [' R% h9 Q2 b% H
查询所有存在name字段的记录 1 G9 s4 _# g2 A7 N$ P
  1. db.users.find({name: {$exists: true}});
复制代码

( o+ h( Z/ W- k' ^查询所有不存在phone字段的记录 # J/ E- Q0 V$ Y1 b
  1. db.users.find({phone: {$exists: false}});
复制代码
0 y$ e8 n8 \* m  D/ j5 F; S

: Z2 z( d+ S! X$type判断字段类型
: m) @( g$ p) b2 V查询所有name字段是字符类型的 5 m7 I" T+ Z) ^4 |2 \5 X4 t& q
  1. db.users.find({name: {$type: 2}}); + M& f# O' k& }! E' p
复制代码
" T- k3 M( j3 W" Y
查询所有age字段是整型的 % K" `& A$ g# ~0 A2 r' j' B
  1. db.users.find({age: {$type: 16}}); ) K% N% A1 |$ E& c
复制代码
1 Z3 S6 ~7 Z3 H, K. ^
对于字符字段,可以使用正则表达式 / ^) I9 T) G" T$ l( d. V3 |
查询以字母b或者B带头的所有记录
9 P  q  g9 M& q: S9 T+ B0 I
  1. db.users.find({name: /^b.*/i});
    $ Y# C! W) s* I! x' ?( m9 d
复制代码
* E1 d3 w& U1 w% h
$elemMatch(1.3.1及以上版本) . H7 I2 E4 `% Y; R2 M: ~: N
为数组的字段中匹配其中某个元素
* ^: @* Y6 \' |
. i$ [( V; Y, ]% ~* r7 Z( |Javascript查询和$where查询 3 D! a# `) b3 W9 m& K. C* ~8 ^
查询 age > 18 的记录,以下查询都一样
$ ~" ~- ~* g- e1 e
  1. db.users.find({age: {$gt: 18}}); " @; w. M* p( g' }/ r7 V
  2. db.users.find({$where: "this.age > 18"});
    2 {9 \/ N  t' p( o% L# N. ^
  3. db.users.find("this.age > 18");
    / }% R! p( s8 R' D0 C
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

- @1 s. h2 [2 ], {2 W2 R5 l: J8 [  \8 f3 y! f5 q+ a3 S+ E6 K! Q
排序sort() " x  [0 D" @+ O$ J# a
以年龄升序asc ) B7 ?. |9 m! {& B5 p
  1. db.users.find().sort({age: 1});   K& y5 |* E" ?+ P, g$ t  X" t
复制代码
2 t# C* P0 _  f( x
以年龄降序desc
; H( A! u  U$ }3 Q
  1. db.users.find().sort({age: -1});
    3 z, b* }' r1 R" u" i1 f
复制代码
: Y3 q# ?( A' A: g: X8 F$ g
限制返回记录数量limit() 6 H7 T2 A9 q( o& r! G4 ^
返回5条记录
  P0 Q' H& ]: L( x7 s3 q6 {
  1. db.users.find().limit(5); 4 \' |- K9 Z, d. m
复制代码
0 ]/ Y& E9 u8 ^1 M+ G! [& C. d/ h9 X
返回3条记录并打印信息
3 Y" U9 s5 G' l! O) i8 Y, f8 _, C# X+ L
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); 4 P; k- h9 r6 V) L1 Q# X
复制代码

$ A( Q. T/ M$ T2 `5 _' d6 f: g结果 7 @& ~+ n3 b, ]
  1. my age is 18
    + ?4 G+ L2 E' X3 C% R
  2. my age is 19
    5 U  q3 M& t5 ?' n' C6 J" x& c( o
  3. my age is 20
复制代码
) t7 N+ e7 U& G8 c: J* J
4 c) j; n* O1 F
限制返回记录的开始点skip() 7 i% h/ y9 Q7 r* D& |, m
从第3条记录开始,返回5条记录(limit 3, 5) / [2 d' D2 [  D" c2 T/ p
  1. db.users.find().skip(3).limit(5);
      E) E% Q7 o' o' Q, c# W0 Z$ j( H% I
复制代码
( W* ]: e5 [% b: {# j; U
查询记录条数count() 0 y8 y1 K2 v0 L+ |
db.users.find().count();
$ ~* u3 i+ q+ C1 u, k. _- W! Odb.users.find({age:18}).count();
& J6 V. C- }5 v$ K+ E以下返回的不是5,而是user表中所有的记录数量 6 J& v" H1 h# c) r7 d
db.users.find().skip(10).limit(5).count();
+ ]! V1 k. Y4 Q8 j如果要返回限制之后的记录数量,要使用count(true)或者count(非0) ' j! o( F9 g% |0 O( ]* X. }
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

, n/ v' K- W) y" Z8 L+ w. h4 G7 s7 S% F! ?3 e- m& D" y1 o
分组group()
1 j! |9 [6 @& {2 _- o) L" r假设test表只有以下一条数据 ( i8 U" E6 C9 E; X: A4 j0 T
  1. { domain: "www.mongodb.org" 7 M5 u! Y- f) ~, a& U9 h
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    6 z9 C0 t( Q& j' g) M- _3 ~/ r
  3. , response_time: 0.05
    1 c3 C  {" k; h% Q) K& f
  4. , http_action: "GET /display/DOCS/Aggregation" $ d4 R# k. g" j7 a+ _1 I+ e4 T
  5. }
复制代码

( ?7 A! z% q& L4 a: R使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; " `3 X4 X5 f  X& ^9 g+ p
  1. db.test.group(
    0 C- d  s8 C+ F
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    9 [  C/ r1 |! a" m
  3. , key: {http_action: true} $ ~' b$ ^0 \! n+ s. B
  4. , initial: {count: 0, total_time:0}   t9 c; N1 o: H" d) c) h7 ^
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    8 T2 Z/ d% J' [
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } ) r8 s6 ], g9 ]$ k- ?3 `) F
  7. } );
    0 q  X) j/ H- K5 y) v* N
  8. $ l9 u; A  l5 d. Q6 A# Z2 N# d
  9. [
      i' x- E8 B' |4 A0 `! V, K
  10. {
    & H& ~( L# f. }9 e
  11. "http_action" : "GET /display/DOCS/Aggregation", 2 [6 j$ J. k( _, Z6 N
  12. "count" : 1, ! x0 ~5 p/ @  C8 a% f! O0 X& O. Q
  13. "total_time" : 0.05,
    & D) b. L. v5 F+ ^
  14. "avg_time" : 0.05 * `, [' C2 [2 \% H. [0 ?9 m9 o
  15. }
    3 o* T& I' R. q% V7 j* F
  16. ]
复制代码

5 d. {, n' h: d) X# |+ r7 s( F4 v! J
3 n( F3 k, d; _& R
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# _7 U& _9 B& K- p, w# C$ h8 T4 B
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
( G% B1 p0 a1 g
$ I: _) G3 Q" ~5 d  P7 j
, ~* G8 F. T5 o' X2 D
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct  }0 M1 h' i3 y5 y3 c0 S& {2 _6 C
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码

9 [. N8 W7 S$ }4 q* A. o8 i3 F
/ m5 w( w1 F8 E9 W# A# q- n  w. j9 {
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

( G' m; B3 i: u  ]. s- E9 ~& }5 ]7 S8 t( ^0 O/ j& c9 Q$ `! t
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
& ~& |" T) l: T/ H" h5 a6 I; t, f0 R

# i( E0 G) C3 @! W8 E7 K+ V
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
* |: V7 |/ l4 M3 v' V9 |

+ }# g3 L5 Y1 y6 b2 L$ v
输出如:
  1.         
    , {. O" u( b" }: z% P
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
7 Y9 c4 M2 \8 S5 a0 h0 `
4 t( T: T" a# `7 L4 \

3 r; j6 e' t. w0 ^
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans", Z5 c3 Y$ @8 h4 s) d% Z" E
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    0 N! C( F# ?% l& C
  3.        xmlns:context="http://www.springframework.org/schema/context"6 w) k: `9 H. n; Y+ I% S
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    5 b5 m, x" Q/ A& {7 Z+ a
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans- u) C, V% K3 ?- z5 c+ N7 |
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    8 ^$ k* M9 X+ G# K' n) q/ o4 z0 Q
  7.           http://www.springframework.org/schema/context
    # I4 R% `9 `* ?  E5 ]( q  L. [; z5 P
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    % X4 W7 x" Y1 F- l3 u
  9.           http://www.springframework.org/schema/data/mongo
    . R# C: E/ I+ _: `* c, t" F2 e1 s
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">% O" j1 F. O, h, j. x$ w
  11. " U# T) i: w& r' m. O" m
  12.     <context:property-placeholder location="classpath:mongo.properties" />! n6 o  U6 [/ S8 u

  13.   Q8 R( D: |' u2 x: c( n
  14.     <!-- Default bean name is 'mongo' -->( L8 H: Y7 \/ \/ ]! z' z: Z
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    ( `" k: P* C4 E

  16. $ U  |' P1 p( C5 ^% q: Z* d4 \# ]: v
  17.     <mongo:db-factory id="mongoDbFactory"
    - t* ~, [0 X/ q! w3 S; v2 y8 P
  18.                   mongo-ref="mongo"
    5 X. g5 n7 u$ P- S* l
  19.                   dbname="mongotest" />
    # w/ n3 r8 T9 p
  20. + p' T; H6 }8 R! M' e# f. Y
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    ( s4 I* \4 n* V: M
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>' h/ b0 p" j! U3 Q( o) n0 K# e
  23.     </bean>: b9 \! P# m1 A7 x1 H
  24. </beans>
复制代码

. U  S8 ?& W  T5 T8 ~' S" s4 W
7 v! p% Z7 v$ I6 x$ X
maxmin的测试
  1. @Test
    # w0 ^2 D" M3 p2 |' `
  2.     public void testMaxAndMinAge() throws Exception {9 y" G+ d6 K& ^5 q- D; T$ q
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    # ]9 N- u$ F$ e0 c0 Y# C. d
  4.         Person result = mongoTemplate.findOne(q, Person.class);
    & c# h, {% Y. @' E& O& Q
  5.         log.info(result);1 f# Y; t+ t$ i5 F7 m

  6. 7 F" e0 J+ i/ }6 F4 ?: P- u: d
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);1 `( X/ {. E  d! ], u
  8.         result = mongoTemplate.findOne(q, Person.class);
    " F8 b& j+ m2 F
  9.         log.info(result);% q; c/ d2 h& V1 q% b6 ^
  10.     }
复制代码
0 a7 F& Z6 j: Z9 `1 i7 f

$ m; h4 q8 {( P8 k- _; I- }9 Y1 P
distinct的测试:
  1. @Test
    , {. [" w( E; G
  2.     public void testDistinct() throws Exception {
    5 v5 F$ v! O# M# S$ x8 w
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");3 q* b7 E2 s3 a7 |, G, `
  4.         for (Object o : result) {
    & H3 l! {. K- ~# q$ P  U
  5.             log.info(o);
    2 Y, T. L4 C$ W# s, a9 v/ J9 \
  6.         }( @9 n' m9 g' |

  7. 3 m, Y4 F; M; `
  8.         log.info("==================================================================");
    3 }2 e: g; w* ^: s$ n4 J0 {3 P( q
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    6 J; ~& A5 C) x
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    ' u; ?0 W) @9 F' t! e& ~9 O
  11.         for (Object o : result) {) p+ P4 {5 g/ J+ j" |( a, q
  12.             log.info(o);  R" U  T6 i' l5 [2 e1 w
  13.         }0 B9 @  I; M% ~

  14. 9 x4 e+ L* ?* j( h5 L! ?: S
  15.         log.info("==================================================================");
    9 k# i9 v. f$ L6 @" g  J
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    7 `# J+ r6 p0 X' R; m" X
  17.         for (Object o : result) {' q- e9 a( ^, P6 d9 y9 ?7 B
  18.             log.info(o);
    + ^9 B' y( Z8 v- ^4 _8 p7 X3 f5 G
  19.         }
    5 c6 }7 A/ i# s- o
  20.     }
复制代码

; `% ?9 ], Z' l9 i, \' ]( u
$ W- Y+ P" L) [% |0 v
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    0 ^# H9 s; a  V+ G! }6 E: s
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    3 V' P! A$ n$ Q4 v. h9 ]
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    5 c4 A* m7 U- r
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 9876546 j2 w% B6 B. M- B0 n# }% V
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    + M2 k# d% E7 x2 z! [, x  O
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo* T( F! ^2 z/ x/ V( i3 H8 U) s
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456$ ?6 a' }$ N; n. q
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================' k) x; `% e0 d1 F* e( o1 E- x" `
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    $ [! g% M/ a" f1 G4 L5 j
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    ! D" |' V7 A( ~; O
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789' y0 d) w& |/ I! m
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    " A- F0 I5 M$ ^. c  K
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    * N' w8 p! E/ t& d" Y' g
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa! `% r( _" v- j9 w. _  t. q
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    8 O; n5 F3 C7 d7 q; M) d
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    $ q$ \# ^$ N- p5 k! a% `1 X
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    9 Y0 f' O0 a. {( O7 P4 P4 B
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx' W0 t  _+ [  ?& Y8 I' x
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    4 f& N: f7 e' N+ N1 X( L
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz: G. f# f1 |" O6 S
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    $ s9 d# _5 {% ?* Z  v& S
  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
复制代码
( a% F2 q7 k  n/ i2 n0 v; V

: T6 [( x: J+ J0 U9 }9 W+ a/ a
这里我要特别说明一下, 当使用了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等信息。
# J4 h" a* m6 I+ |

/ j# R# `) v6 M8 u5 W$ P! r4 s* {/ q/ T+ y, s4 a6 n( T
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-3-16 18:19 , Processed in 0.070160 second(s), 23 queries .

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