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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:3 A% n/ U) b0 w& \2 f9 j
0 z* Z& X8 ], U/ J" P  x
1 ) . 大于,小于,大于或等于,小于或等于) t- V5 n! w/ R8 h: g

/ Q' s5 ~- t- H) d. {$gt:大于
- S6 {% D) O) r/ E1 e* h$lt:小于
; g: _* j7 z7 z9 T$gte:大于或等于
6 w2 T0 G* P3 h3 u) i  U  d$lte:小于或等于
$ K2 l1 h' k. w& g3 r- d
: w+ i. b# C$ }例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value/ e4 [7 z$ L) O! P
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    0 `4 |5 Z4 {- o8 a2 o
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    1 Z5 [, a) @- b6 K
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码
/ {  m7 m  Q! D0 J- x
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});7 U% v+ _8 [/ D9 |2 D% j! N
  2. db.things.find({j : {$gte: 4}});
复制代码
" {- J$ R# N* o; z  A2 r7 R
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

# J* w. q) @" U
2 i/ v& G4 [' |5 X+ t6 R0 _% N8 R8 R$ H; D
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

( N6 p' H, F# r& F% f. e" [
3) in 和 not in ($in $nin)8 v' c8 [2 y2 Y- v! {& }

% x+ l8 ?: u) f9 E2 e# y/ G  W语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
7 B0 L' ]. c6 {2 |% F2 [6 s: \, Q
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    & f& S' t' @+ X8 R
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
% Z0 p' {' k" q2 c1 b
! f  \3 {! F3 }' Y& p2 \
4) 取模运算$mod
. U; V& y+ C: w! p  c) t: I( {7 y* w& f4 L0 a
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
/ @) N  k& k5 S: y
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

9 a, k: {0 E7 M% `# Z  W
( |6 r) l( P8 D  g4 j
5)  $all
2 M+ T: k7 a$ U4 k; i  Q. U( B7 y# i8 o7 `1 H: v, \) d; ?
$all和$in类似,但是他需要匹配条件内所有的值:" p0 H# e% }, z0 Y

8 c" j/ r# I+ H' Q3 h) Y% U* |如有一个对象:! g, i5 Z$ U. f! i' l
  1. { a: [ 1, 2, 3 ] }
复制代码
6 z! U& x- s. j& K
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
" W! I$ E8 s  u, n
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
4 G6 o% e: _" H$ S% Z

6 W, ]6 C. R7 H, w% _- f: A# A6)  $size4 p7 {) a) h/ `/ j; M
2 Z! l( L4 A! R' d! S3 b7 O
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
. ]0 r+ Z$ P; J) p' L6 {
% Y* Y7 g5 ]' W1 j. b+ [4 b下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
1 F) V9 f9 c1 D, m
官网上说不能用来匹配一个范围内的元素,如果想找$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.
3 Q, n/ e) y4 ^2 J/ t3 s0 }
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    5 h5 r& Y: ]  G/ c$ ^
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
- p$ m9 `4 Q; s6 Y# Q  L
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string; ?& s, \4 X3 c; G
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
9 {- j3 X1 [; `! [* m# I+ W4 T
9)正则表达式6 [; e+ r( O+ O/ W

3 q% E" k  {' c5 J" _% Zmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

+ r4 [8 I4 |- p& v$ ?9 D7 J! c- d
10)  查询数据内的值$ ?. A# q- n7 h

/ C& J9 x( ^3 c. H下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
7 G; k2 @" z# ?- ]# h% x/ H
11) $elemMatch
5 g" m# R% C, V) P+ V; v. R) s# m0 A0 M; ?& I6 [
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    $ j8 L: S8 n5 R0 u% O6 g
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    4 a; Q* ~0 d) a+ t. ?- [
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]& z: ^2 P) w2 `6 |6 s  T
  4. }
复制代码
7 Q6 F2 D: C; I) i# Y% e
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } ); `& r7 ~4 U5 Y5 Q1 c# D+ \
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
% i4 M' t2 M/ Y9 K4 P& j7 J" q/ c$ T. ^" K" X
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码

1 [. R( d! q6 ]& E$ i
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

/ o( ]* S5 M6 P5 g# b
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

4 t2 ^# u% j( h& U
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

) h2 o' e4 [) ]
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

$ C) b0 ~; e& Q$ e# O" q
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
/ ^: I( l* z0 y
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );" j" ^  ]4 p( E2 a
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

0 S1 a' |1 H: H
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
8 a2 {* m) X% U# s7 V3 I4 e: {8 S
# @* Y; p( B; @( @/ z/ Rmongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
5 }* D( m& i( h( b7 L1 O5 T$ M4 Z/ R+ G; f6 s$ V
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
& [8 ]) g9 E+ [' \( M) ?4 M7 f& N! c8 m) a
版本二:
/ x* c, R( h( m$ A5 }# S: `; d
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
+ R4 F9 }  M4 ]& c& }& O, J, E
  1. use admin
复制代码
* f7 t* j, _% v& ^3 X& R
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
* _: a+ N7 C( ?/ c6 Y
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

( Q# e: S4 c4 ~2 t' [; z6 r
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
. d  ]! v; h1 Y
         5. #删除用户
  1.           db.removeUser('name')
复制代码

$ O0 n; Q$ l$ E/ g; Y5 n% c
         6. #查看所有用户
  1.           show users
复制代码

0 Z5 l, x5 Q# B; Y
         7. #查看所有数据库
  1.           show dbs
复制代码
3 e& l: t7 |: z( r0 G. B2 b# @
         8. #查看所有的collection
  1.           show collections
复制代码
, i3 `; l7 P7 v3 ?* w2 A
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

! B! N9 y! R. h: p6 G2 Z5 l
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

- K& Q+ V7 U  `, m  D( `
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

, J' i/ d6 @8 y& Z* y/ i1 U8 G
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
# B% J! Q' K- b4 q% G! {& @. P) ]; j
        13. #查看profiling
  1.           show profile
复制代码
6 [' E- L. {# \( b
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

( k- l7 A( ]. H$ {
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
9 ]3 K# `6 H% X: x; D% z' Q  m
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
8 m& _& ]5 X# u6 W
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码

' {& c0 ]$ s; I- n' S) z
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
- c+ _- E& a( h& |9 Y
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
  c3 r- D8 Q. g2 D1 M5 Q
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

  O. T2 m0 V6 j) F2 R' G8 j2 f; l
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
9 P$ w2 m" ^% l/ [- ]1 F0 w
   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()

- i! K: ^* X% F4 p0 m6 N# }
6.  高级查询
条件操作符
% x( `9 R0 l: r3 A- _0 A5 H" p) a) p
  1. $gt : > 5 v! Q1 x7 x. B% t
  2. $lt : <
    & d; Q5 s+ p* z- Y
  3. $gte: >=
    + P6 G" e) i6 Q. X. f7 f- ]
  4. $lte: <=
    ( {2 S" I  S, d% B
  5. $ne : !=、<>
    2 ?# S- f, ]% n3 d
  6. $in : in
    - Z; c5 z9 ?4 T* L0 E; b
  7. $nin: not in
    - N3 ]" I# {/ v4 D
  8. $all: all
    2 l3 G6 {' q7 {, O. N* y3 j' D  K1 P
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

- D' H0 V6 M$ S% m* q  k  X
: {0 _  W3 g, x0 r查询 name <> "bruce" and age >= 18 的数据 7 B2 L! {) ~0 I' r
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

; `* ^3 R6 U! C
( R. ~" D7 ?, l: Y. l" g查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 ! y* Z/ \0 |- {8 G, v
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

1 k, Y- Q/ n, ^: z  y+ q2 r, e1 W6 G1 \# E6 U2 V
查询 age in (20,22,24,26) 的数据
- G, F% |+ _. l7 o: Z. ]& M
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

: g4 A5 |9 E+ f9 p) @  Y; E  f; |  _
查询 age取模10等于0 的数据
4 _7 S2 R  a6 g5 X: A- ^) o3 L  w
  1. db.users.find('this.age % 10 == 0');
复制代码
  ~7 y; f0 v& p! ]: L9 }
或者
$ A9 N' V- J/ d* `
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
$ O3 F6 l$ a, i1 u- [$ p2 y9 g' M( B
* c8 h8 E0 _3 f
匹配所有
4 T% P: P# ?5 @( M3 e
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
. |& L: n% p4 Q
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
/ g& ~8 j* ]3 u. u5 Z可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } * p( _: B* c$ M& K

* Z% k, `  }6 @) I查询不匹配name=B*带头的记录
& r1 U1 k$ h( L% U! n1 O, h
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

- X: ]+ S$ ~- U9 W- D! l( j7 p查询 age取模10不等于0 的数据 # p2 c; ?- F! M! S* h& ^5 s
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
9 s; z. B6 e9 v& M% @& c
2 d: W  [" o* L" I1 z3 j
#返回部分字段
  v& }+ g/ X. ^1 Q9 \选择返回age和_id字段(_id字段总是会被返回)
& F- ]4 l" T' c" w& M) x' x
  1. db.users.find({}, {age:1});
    5 O8 g6 P& T6 Q6 B" F. m
  2. db.users.find({}, {age:3}); ( ?; c4 U2 k* H$ S* E3 ?; ^3 K7 j
  3. db.users.find({}, {age:true}); . G2 n6 H- F: F1 ]" C
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
6 }  }2 j% c/ A  @) `/ D: d
0为false, 非0为true , a8 `; ?% A* h1 F7 V

4 S; Z7 ]4 W. T' `3 {+ J+ _3 n: @选择返回age、address和_id字段 $ y0 U' g7 x8 U! w4 S4 ]
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

7 L' c+ f( W& O% ?. |, Z. K6 x1 O0 y& u: v9 }- @+ P- @* W! J
排除返回age、address和_id字段 ) X* P4 I  X, G) o  j4 O' L' S- X
  1. db.users.find({}, {age:0, address:false}); 1 k" ]. B. D' W0 r$ ]' e( b" h
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
! O( w& z0 R7 K% j6 o

/ i& f8 ^9 B0 o( a" Y% Y数组元素个数判断 % H9 P6 x/ r& W& |9 x" F
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 ) T& M9 L' X* |; p  {# f' t7 B
匹配db.users.find({favorite_number: {$size: 3}});
1 @) u/ Z+ d9 k  U  E7 b6 o% O不匹配db.users.find({favorite_number: {$size: 2}}); 3 K! c- ~, H& b! Y; C$ n
% f5 y! w% s$ d
$exists判断字段是否存在
- e2 n: m1 V0 e查询所有存在name字段的记录 $ S% i# B3 d0 z" a1 s3 K
  1. db.users.find({name: {$exists: true}});
复制代码

  M  ~2 u4 q7 H( i( }查询所有不存在phone字段的记录 8 _% `* `! Z' p
  1. db.users.find({phone: {$exists: false}});
复制代码
: _2 f0 ^' D, f- d; j! q
5 j/ e. @' b6 D5 r2 P: @
$type判断字段类型
- ?; K( z/ t  d查询所有name字段是字符类型的
9 V+ |- _' P; ]& P6 s
  1. db.users.find({name: {$type: 2}});
    8 j3 ?3 Z# G9 s. u0 g! g# m6 L7 Y
复制代码
$ C- m# l0 L  {7 P
查询所有age字段是整型的 1 H( D- `- y! N$ x( s! b7 U
  1. db.users.find({age: {$type: 16}});
    ! Z6 t" p* l" ?! H3 a$ M
复制代码
, Y  N  Q" x7 Q, {4 x5 O( O
对于字符字段,可以使用正则表达式 0 e1 R% J! b4 g, B' ]
查询以字母b或者B带头的所有记录 - u1 H1 f5 f' I
  1. db.users.find({name: /^b.*/i});
    , I0 E; M$ c' Q3 U1 N9 z2 h
复制代码
5 m4 h/ y2 X( ^( b
$elemMatch(1.3.1及以上版本)
9 x( C) W9 R* {, S2 i4 W5 c为数组的字段中匹配其中某个元素 4 s" Y  [8 d- g  D% q

) t( v5 B, K0 b, N9 v# ZJavascript查询和$where查询 ' _& B' j7 Q3 i8 u+ X
查询 age > 18 的记录,以下查询都一样
+ P! i6 L& o( U% E3 L% L+ h
  1. db.users.find({age: {$gt: 18}});
    . `. H5 R3 T8 X9 i: Z; g0 K
  2. db.users.find({$where: "this.age > 18"}); 8 d2 B+ L4 E& A) @* Y4 `- F
  3. db.users.find("this.age > 18");
    ' ^4 M/ U( s" b8 A' J3 u: s
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
) @+ z6 Q. p4 }" C) u

: f6 _# h- B) O2 Z排序sort()
; n/ N# R( K/ Y) a; w/ e' _6 ^以年龄升序asc
, U1 z+ R5 q5 U. ]! b9 `
  1. db.users.find().sort({age: 1});
    9 U  G: f$ V, w8 {
复制代码
  F) c# m" m7 @9 M4 `' ]
以年龄降序desc . J) K) z* ~; A) s
  1. db.users.find().sort({age: -1}); , a& m- y. _1 G" S1 z
复制代码
3 t* h7 l( ~. Q
限制返回记录数量limit() ) m7 w. h" a+ t  M1 ~
返回5条记录   }# d! t9 e) @0 v# [
  1. db.users.find().limit(5);
    / k8 O6 M" h' B; `% U
复制代码
& \1 b. @9 t* {2 S
返回3条记录并打印信息
' n( ^, ]+ O; ]" b
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    0 N1 o6 C- ?1 z' Y
复制代码
" Z7 ?- k/ o, k. V7 e: P: q
结果 4 x6 d! t& M  m! J+ ?
  1. my age is 18 8 C( ^, Y) M6 J* l, n$ @7 E
  2. my age is 19
    ! w$ @& C1 L7 m( C1 s$ N
  3. my age is 20
复制代码

- O% f) k, j! w+ F8 C" T
. {  I8 H! v" ?3 D限制返回记录的开始点skip() . \% Q* N4 Q7 b% T8 X' e
从第3条记录开始,返回5条记录(limit 3, 5)
7 ^6 l; T  u. Y' c1 F/ \
  1. db.users.find().skip(3).limit(5); & N. t. V7 s; \( C) s) P- p% i5 A* o
复制代码
1 S/ Y4 t  n8 S7 _
查询记录条数count()
: h9 v. k$ x: jdb.users.find().count(); ; s* h4 C% a* a/ E( s
db.users.find({age:18}).count();
3 b/ u. O, G/ T  b. m- g' e以下返回的不是5,而是user表中所有的记录数量
2 p0 R$ n9 S" n" mdb.users.find().skip(10).limit(5).count(); 5 I$ D, T3 z. g( s8 k  M- S' N. j0 {
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
& c" L" ?- _3 E; ?: F8 T, G# J
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

6 I4 x, q/ ~: y3 A) U" C8 G
1 h" @. q& m: J. A分组group() - C# ~9 V3 X( u. b. W; X" T& x2 d. {  L! r
假设test表只有以下一条数据
8 W& ~- y' [3 \# e1 e
  1. { domain: "www.mongodb.org" 4 Q+ ?; [+ u2 b8 R) p/ x% W( n
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"}
    & h" M+ w5 X& e9 u  P
  3. , response_time: 0.05 , {; G$ Q) `. Y9 J- d& X& _
  4. , http_action: "GET /display/DOCS/Aggregation" ) p0 m' a9 E' {$ R: s6 q
  5. }
复制代码
) u1 e, p; }2 Z: \0 g! L* q% {9 C
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; + ~$ f( t7 T/ C+ y6 ~# w2 d4 e
  1. db.test.group(
    5 N/ H% ?* y9 ]9 k
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    8 e( o4 r4 }3 L
  3. , key: {http_action: true}   l0 |& N! S' {3 l) I+ b
  4. , initial: {count: 0, total_time:0} 6 d. u3 P+ S* k6 G3 W; R+ x
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
      ~, ~5 m) x- {* `4 O. P, [
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    ' U" P: G% a) k/ ?$ T. t* i2 e) i: t
  7. } ); 3 ]- C  C  n, K) V; e
  8. 3 S# \) j9 |* f& e
  9. [
    7 C, I1 w6 R$ {# I8 L( N+ _( e
  10. { 1 a/ s3 E! W6 F4 X
  11. "http_action" : "GET /display/DOCS/Aggregation",   P/ w0 n# O- e
  12. "count" : 1,
    9 w' _7 p# ~4 h& l/ |7 w: y+ T: H
  13. "total_time" : 0.05,
    0 u* y; H* {' m
  14. "avg_time" : 0.05
    # o, I% O8 N! a9 r9 {+ x
  15. }
    1 I% C7 T8 A3 k
  16. ]
复制代码

3 Q$ P% `; E' s  h9 T4 ^5 F
7 l, g& R# \+ o2 T0 G$ D! H
! u/ P1 n8 Z6 W% y& @5 K/ gMongoDB 高级聚合查询
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- Q) ?( k# A: z5 s5 P2 v# V
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

% p# }9 B# m, Q, s" c, J  ?, O
( A1 z1 ~, i; z+ ~  t

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

" l% g- f4 k; w: j+ N% m' T& T' ^
' s/ [" j, Y; q' Y
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

8 a- E9 u' A/ h$ a2 l) \5 M) Q4 q3 ^' u( H+ z8 \  w
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
* _' y/ d8 p6 c; l

8 b  w8 _8 J( G1 S0 o6 d0 @2 j
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
3 X; S: W# z( M# |4 {2 ^
, Z2 n' {* O) |6 u
输出如:
  1.         
    2 l1 C) U9 w; D0 ^
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
  E4 {# n  a9 V7 s; W
4 P8 @; q, e& }  }: K( j

+ A3 K8 z% [; ?2 S
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"2 J' s+ n+ {$ {# w% w
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"- f3 K; N4 W  V" l" P
  3.        xmlns:context="http://www.springframework.org/schema/context", Y- T  u, \- W' I- w$ r9 h
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"/ F; y+ {* @- _7 S% w9 a5 ]8 }6 F
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans
    ! t6 H. s$ C- f% q) U
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd; A" M/ n4 [, X# B8 {. }
  7.           http://www.springframework.org/schema/context
    . A1 C, _2 M/ O3 [$ h! K- G
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    ! Z5 }( A! o3 U5 R. y' Z6 }
  9.           http://www.springframework.org/schema/data/mongo& d. d6 S2 O1 P& Z& \" ~9 O
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">9 @3 R6 V  ~- J" @- h( d# }! d

  11. 4 D7 }" ~) x' R3 ~( u! ?) z9 |; D9 T
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    1 u* m4 R$ N8 G+ n5 i8 t

  13. . Z6 @$ Z! q% e: r: D, ~! |
  14.     <!-- Default bean name is 'mongo' -->! u4 Y4 W! z# I* X
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />3 @8 n' u; g4 v3 ~/ p
  16. 9 c, y" i* ~2 r$ w, ^7 O4 A
  17.     <mongo:db-factory id="mongoDbFactory"
    + P# t) U# s; u
  18.                   mongo-ref="mongo". r. i7 f# }$ T5 z" _. {
  19.                   dbname="mongotest" />2 i' n5 L$ b$ z3 x
  20. 4 X# Y: `" q5 e+ M. v3 R
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">, G0 Z/ u4 i' E4 r
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    ; n% f7 a# e5 F& G! h  L8 V
  23.     </bean>8 ?4 Q! ]4 w( t. n
  24. </beans>
复制代码
: s9 A4 `& u0 P7 x/ c

! y5 H/ k, m3 ?  M& R& Y. B7 P
maxmin的测试
  1. @Test
    ! }: r/ B& {+ J# C- P
  2.     public void testMaxAndMinAge() throws Exception {
    1 x# \" i+ j. l% B) n
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    8 \3 f8 [  z6 v" S4 b
  4.         Person result = mongoTemplate.findOne(q, Person.class);
    ' ?4 `3 s% O8 G7 p; o, ~  n9 o; R$ G
  5.         log.info(result);
    1 E# I: _; u; x5 d

  6. - Z( I4 G! e7 J* o9 j3 @, d- T
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);4 Z1 L  k$ o5 t% ~; T
  8.         result = mongoTemplate.findOne(q, Person.class);& Q7 w: G8 ?% T& H4 o( u
  9.         log.info(result);) D; M* e( _; M& \+ V1 G* k
  10.     }
复制代码
. H4 N; E2 h, @+ U& d: j4 N) H% U

6 K6 R8 o1 N5 q; H$ S4 L
distinct的测试:
  1. @Test( ~4 c# O4 e& w& Z# [  h
  2.     public void testDistinct() throws Exception {  ]9 i" z; G0 H3 C9 a  X: f
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    : H1 n! @% n: _7 {7 k' U% p2 n
  4.         for (Object o : result) {7 R  k4 X6 q( ^" Y( x3 w
  5.             log.info(o);
      @) {9 E3 X. T- x+ k3 c$ n
  6.         }" }" \) z% r0 p% ~0 V0 n4 M

  7. ! z0 H! n0 |5 }4 |
  8.         log.info("==================================================================");* t, u! ?+ a! I5 m, o. P
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
      M- x# k6 X: l: a  @
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    2 Z5 q4 y7 Y3 ?1 g( S7 m0 X' _4 s5 m2 c
  11.         for (Object o : result) {
    % E9 y- D6 V) m: n! |7 d" `
  12.             log.info(o);
    4 s0 T4 G: h7 C
  13.         }
    * @) x$ A: _9 v4 u

  14. & J, {& P4 {( p3 i7 J4 u& _
  15.         log.info("==================================================================");
    9 w  E  \- g! {2 C9 c8 Q# n
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");* y. ^% ^( P; o4 f9 I  B8 d  n3 U3 o
  17.         for (Object o : result) {
    0 I; h& w# x$ s- E2 Y
  18.             log.info(o);% B. N( e8 d9 `0 j
  19.         }
    6 w$ }7 u' h* J0 ^, T; T2 d
  20.     }
复制代码

3 D, l9 s$ |* x; {: G; k
1 k$ |$ N6 [- x
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    - m& R8 J: u5 h
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 3456785 m1 Q& I% d, }3 d. O. S
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    2 u: R/ n. C2 Y) E. J/ G( `7 ^
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654  z; I4 ^" q0 c# @/ f
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    1 e5 i2 G- z7 I
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    6 b3 j7 v- y* {& L" c( g
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456& ~) z! r. ^& g/ b9 Y
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    0 [: [  O" Z% ^0 H5 x1 o
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    & E# x: M% w5 u  S$ H
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678; D" P+ Y. L! I( U
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789* c' b' K) y4 `; m5 g
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    ' O; s" S- ?5 j7 T0 ~
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================9 S1 S2 n- b9 t4 h, N) Z
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    ! \! l) [" f% H$ M) `) I
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    4 ^/ i) Q5 K2 |, t8 s6 R
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc4 U" w! a3 \; N
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    ) {; I: p2 y: j) q- k/ p
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx3 L1 d3 Z8 Z$ F6 U5 O# n( Y/ j$ r
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    8 w8 t( k( a5 D( ~- ^0 k: _8 t
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    5 h) n) L9 e; @1 E1 x5 ~
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    ! ]5 n5 J' Z3 Z+ K* x) [
  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
复制代码

( H8 |! |$ O& C0 Z6 w
2 m, u4 L4 e' ~: K' j6 a" f
这里我要特别说明一下, 当使用了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等信息。
  b: K+ i. B- C3 S

% n  k* V8 k* g( z
3 G$ a/ U) a( q' l
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-1-30 14:27 , Processed in 0.066928 second(s), 22 queries .

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