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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:
# B2 E. N7 D2 `) p# d+ ]+ O( l& v' B+ F
1 ) . 大于,小于,大于或等于,小于或等于5 p0 u' Q9 R  B6 e" J9 H/ Y  x& f* m, I
" ~: H* L: n# ~8 X/ ~
$gt:大于
0 }5 a$ S# ?  Q$lt:小于
9 L; _) C" P1 T, n1 I$gte:大于或等于+ u: x: v8 ^  A5 o  J5 m8 o
$lte:小于或等于
9 M" \2 H# N8 H" I: B3 F8 F7 N! W; e8 l2 I5 H
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value; {  G+ W) `9 d3 W" R
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value/ K9 F) G5 o% e& Q
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value4 p* F, D8 ^" G- g6 e
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

: D5 `# H; J& G6 s
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    # V" \3 F' `! |6 f: k! G7 @! F
  2. db.things.find({j : {$gte: 4}});
复制代码
/ H3 k- ~) r: h4 o; z
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
/ |# \+ {' o" z) L  F  D  `
3 e" m) v: q, l5 R" M/ R
2 H/ z7 `/ L4 t$ ?
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
5 Z1 @0 `1 E2 O. u" b8 p7 {& M
3) in 和 not in ($in $nin)/ ]9 a: \8 o( }; u- g  D

+ N$ N9 [1 `0 v/ [+ E, ]3 L语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
3 U  f& w5 L0 ?4 s8 ]# o+ X* t
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    " C+ |: G* S2 g; ^# `7 ^6 J# p2 P: ~
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
5 x& u2 @0 i1 U

  Z- |3 F, Q- ~+ }  h( n; O8 ]4) 取模运算$mod
' b% i9 s* X! N- f8 J/ i
" w  l: R) E7 r- D8 A% u如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
) R$ M- C% t7 t: _) D
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
; r9 }+ f* N  m# b( t: `4 K! U

) \2 h; D, |% ?0 H! P5)  $all
: s) \- B( k7 A) o1 i- B; b. T( I+ ~
$ V) j* f& h7 ~! l$all和$in类似,但是他需要匹配条件内所有的值:
+ }7 Y# w3 L$ p9 q  F/ A6 Z, `
9 I9 I* V- M$ x( F5 Y# ^如有一个对象:3 H7 L* l, z* ^) C5 l
  1. { a: [ 1, 2, 3 ] }
复制代码

, ], ?' [7 t4 {4 o2 k! v
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
/ R. W! a; b) X0 h
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
, H# n9 ?  M! V5 t$ g

* S* c1 K' s/ q1 {. W9 B6)  $size
3 ^) [% w/ w" c$ [  f% F
9 o& Q1 I5 h8 L6 ]$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
* `6 l1 w5 @. @+ ]0 F
: z: x3 T$ c4 |3 `3 v0 C* j下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
) N) o* w8 I& x' f- H8 T
官网上说不能用来匹配一个范围内的元素,如果想找$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.

& K0 g( l! k3 U( K2 v
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回7 A; t9 P$ s" ]% I* d+ S
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

/ M: J# b' C6 M
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string- d; B$ H5 @1 [. [+ f$ T3 Y4 H/ k
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
- w2 ]1 U4 K+ Q4 ~3 W: G6 j
9)正则表达式
& w2 |3 Y7 ~( L0 P
5 E4 C$ w" T1 [0 amongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
$ K  L; U. \6 r& _" n: C
10)  查询数据内的值. |1 e) @1 ~5 k% N# p8 H. L

: D' g) u7 A8 \" X; b5 n4 k# ]下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
/ Y5 \1 ^) _- T. P1 f* L  M& F
11) $elemMatch
+ }1 U% I! u6 ]: a) u( L
, ^2 r  c  f3 T1 M7 i7 x如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 2 a# v- E" N1 j
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  - q2 J( h3 V5 Q
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    9 u0 O+ A8 ?; `8 D+ D9 E: `& L
  4. }
复制代码

, ^5 ^1 K) a1 @( \; z& Y% x$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )  z. S. n* A& Y. T7 j# T9 y! y# n
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }   ]7 r6 v4 u+ L
& W2 A7 A: R" ?" @
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
% m* g4 G1 _. n+ J3 B
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

4 M, U- n6 d' O) R% `) j( Z
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

' Z4 [, ]5 y' ~( J9 j# D* b8 ^% n
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
% j, _/ c/ a( B4 D  ^; q# K8 \" M
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
; Y2 g; A+ A; t! ]
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
4 L; k  }2 m6 L/ \% l& U
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );4 [9 b+ R+ Y6 a# T. Q( L' O+ x4 B
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
$ v% Z: @0 h/ v( L: u1 }
mongodb还有很多函数可以用,如排序,统计等,请参考原文。" h% F, X! H2 Q0 M6 `2 |
6 y8 J# I4 @6 O& p+ Y
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
5 Y. g0 |% L! g4 X! N# j; A# i, |+ L( e7 ^
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions3 F- U' E. h# s7 N- \# F
9 a: h* }% l0 U- B
版本二:
1 g4 i& _+ ^8 l# O0 h6 I9 W& d
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

1 p& p9 f& y. i8 ~" j1 D1 f) h
  1. use admin
复制代码
. V, `+ i  M' q: u
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
4 I4 B0 @, Y% @- S
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

5 n7 {3 s0 ~6 i( n. _) D
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

0 a/ I# h& x, `  O
         5. #删除用户
  1.           db.removeUser('name')
复制代码
7 R' e' O! w' s/ y
         6. #查看所有用户
  1.           show users
复制代码
6 ~: d0 w2 W3 N2 n
         7. #查看所有数据库
  1.           show dbs
复制代码

! x! N: m' c. ~0 H
         8. #查看所有的collection
  1.           show collections
复制代码
2 a- }- o+ S7 e: G* ?; G
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码
  V+ q, U) v. ?( R
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

+ k4 O) [5 K6 g# t; l
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
5 P) A/ t1 a: ~4 A6 W9 Q$ X
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

1 g; A; b  a* H. E' c+ ?" f
        13. #查看profiling
  1.           show profile
复制代码
* g9 k$ N" z4 k$ s
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
! a+ X) O' T# l" |- W9 ?; |; K& Y2 j$ t
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
: D7 E9 o- G9 F. d# m9 e
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

, {% t0 I( e# a; e, @' g/ `1 e
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
/ X$ a& u; G1 }1 L6 |5 `+ H: c
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

% L0 }* B  g. D' t) h- e
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
% c, a. f2 e' r& G; C1 p0 T1 @
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码
/ C  {& F" I) J* x' E! ?) u
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

5 A3 |. R: ]$ B' O! n, y' r' Q
   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()

9 G7 p! C* T! {7 D( h2 q
6.  高级查询
条件操作符 ( [3 T1 G* j5 b, h* e. |/ Z6 J
  1. $gt : >
    , i2 ~0 }* D' }
  2. $lt : < ; R# D4 @; f' C
  3. $gte: >=
    ' }. a& J) ~( @* [! ?
  4. $lte: <=
    1 s0 h( E" ~. B* o4 I/ y8 y
  5. $ne : !=、<> 7 V7 G" L& M! g' {) s2 u% N
  6. $in : in " J& H! b0 C) u+ p! m6 J, y$ R
  7. $nin: not in
    * j: x8 Z* i# k$ b
  8. $all: all
    ; P2 I5 h$ i) D, [; e1 _9 l
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

" N' ~( `6 L: p! g/ {. [8 X6 o6 T; \. @8 Y; n+ \
查询 name <> "bruce" and age >= 18 的数据 . d: q5 ]. n, a$ U
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

+ S+ B  m" P- G. n/ p
& d# u9 [7 R% X$ X& |- O2 B) O* Q查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
& |9 E3 ]' u& f' @9 F; ^- ^$ n
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

% ?8 I- F- G! H: S2 z
# `9 j) A! g+ ?6 U6 j2 {, Y; ?  o查询 age in (20,22,24,26) 的数据 1 y" r8 P" J$ ^# r: n0 w( @
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

) @% L0 f: s" u( e% |) c- m0 p
5 o( V8 W& J! i2 Y6 Q- D查询 age取模10等于0 的数据 ; m: Q- ^8 T! `; h
  1. db.users.find('this.age % 10 == 0');
复制代码
& s4 G7 u- E. e
或者 5 y0 i6 d0 b) D: f' n9 A
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

3 ^1 r$ t- W9 m/ `1 k5 `5 A' }2 S1 u) Y9 {5 z
匹配所有
1 Z+ F4 u; E" t# X- T& ~
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
3 k, f! o4 `4 |+ X' Q( o
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } ; f* v& V* |: P
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } $ T5 m: z( p9 N% L' }$ i- k

' T- R3 I, w( H  s- E6 |查询不匹配name=B*带头的记录 1 o  o0 j( b, p' T, {6 @; W; ]
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

% p$ ?- i, P' e) t% f0 Z: D查询 age取模10不等于0 的数据 0 V1 A" h9 _) C2 C4 ]  y
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
! A4 q+ o+ S& _9 f/ C
* V* ?% v4 W% Z7 W9 M
#返回部分字段
4 ?! W; ]! m: x选择返回age和_id字段(_id字段总是会被返回)
4 m+ k! h# x! A% e; `& l7 s
  1. db.users.find({}, {age:1}); & d5 u3 R2 P  f# N, }  X
  2. db.users.find({}, {age:3});
    ) r" J# f4 j% P; x- C
  3. db.users.find({}, {age:true}); 2 F# t$ m+ y: C" n
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码

6 G& E/ N' w5 G3 i7 r0为false, 非0为true
' k3 \9 E1 h) R
8 ~$ [+ C3 ]6 ~* i1 W选择返回age、address和_id字段   n8 |% J1 `$ s$ N  T/ J4 T
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
1 N7 }% x* P2 e+ N

+ w6 n' {/ H) W# {3 w排除返回age、address和_id字段 $ P" {. `) O$ l3 p6 W: k& o9 Z
  1. db.users.find({}, {age:0, address:false}); - H+ S, B/ B; w
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
# i$ a7 ?0 j# c9 e0 [, ]7 |! i

* R3 r* q: o% G* S) x0 B数组元素个数判断
1 e, ~0 L; B# {0 C$ W* `对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 8 T' J6 D# ]- u) L& N# e
匹配db.users.find({favorite_number: {$size: 3}});
1 w9 c4 y! g7 ^  L8 u不匹配db.users.find({favorite_number: {$size: 2}});
  l* {% |& C- ^) ?6 u+ E' y  v( z- g
$exists判断字段是否存在
; J5 R$ w; E  |/ Y查询所有存在name字段的记录 ; j  k* j* k8 t! {$ q
  1. db.users.find({name: {$exists: true}});
复制代码
7 f& ?: t# [! X5 u; x7 C2 L
查询所有不存在phone字段的记录 . {3 N5 n$ o$ g, D
  1. db.users.find({phone: {$exists: false}});
复制代码

& g5 w2 R! Y8 P: N2 N( A3 o- _6 q, M* C6 S
$type判断字段类型
: z+ x% L$ C2 F7 `- d查询所有name字段是字符类型的
' @+ W' L+ e* b2 v: i
  1. db.users.find({name: {$type: 2}});
    ! u! l4 ^0 D5 M+ J* I8 J: G
复制代码

5 X* r7 h" X! T查询所有age字段是整型的
  S" h$ D% X  \8 r$ z$ Z
  1. db.users.find({age: {$type: 16}});
    4 Y* `+ }* J% b- P2 Z0 ?7 |
复制代码
" L  ~3 A" ^+ `1 j, A
对于字符字段,可以使用正则表达式   W9 }* H  s. q2 u$ O1 h
查询以字母b或者B带头的所有记录
/ W, q( W/ k# R
  1. db.users.find({name: /^b.*/i}); ! B! {5 G; l7 C
复制代码

& d4 u) f9 P3 Q) @4 v$elemMatch(1.3.1及以上版本)
4 {( t! ^- z5 |* t为数组的字段中匹配其中某个元素 . I" E% Q: u% \) R6 I' N
" @9 A4 e% L) ?$ z
Javascript查询和$where查询
* _& f+ Q; \8 q& R查询 age > 18 的记录,以下查询都一样
5 E, Q/ N4 w+ C& p% d0 L! l
  1. db.users.find({age: {$gt: 18}}); ' G+ x, `* @7 l) w
  2. db.users.find({$where: "this.age > 18"});
    - l9 x" i5 V' ]3 J7 V
  3. db.users.find("this.age > 18");
      z/ O$ t: P1 s4 \/ t! P% N6 w7 T
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
5 O. P+ A! B* ~9 [

5 p: [9 \. t. r) p排序sort() . M5 p  d& G1 i$ g' A% W* |) V
以年龄升序asc
0 r; Q  z) h: P4 O
  1. db.users.find().sort({age: 1}); % e3 B4 \( l+ ~; M; h
复制代码

' P4 z2 k8 `" p8 V8 I! i3 I& C以年龄降序desc
% b8 |- P0 L$ F5 J) _
  1. db.users.find().sort({age: -1}); # a: E: [# R2 _; E$ i3 ]
复制代码
) s) o' c4 H& Z- j& F
限制返回记录数量limit()
/ T& Y# R/ F  Y( }9 t; F返回5条记录
: o+ T3 `" t7 W3 t- S
  1. db.users.find().limit(5); % ]% }( f& {. S
复制代码

# t% U* A1 A2 d& N; F9 g返回3条记录并打印信息
; W8 B& U5 Q/ |$ q5 e! e' G/ T" ~
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); . _9 w3 g* Z) P' y' p  L, u- G
复制代码
& X$ C8 n4 F& [5 ^) ^9 {6 T* d
结果 6 k9 ?+ n/ ?" k) K; j
  1. my age is 18
    2 N; _, g$ U. D3 L
  2. my age is 19 0 A7 J! C. z9 `8 \
  3. my age is 20
复制代码
+ p* q  e8 W" @* T) B

6 g3 F! H% \, ^  P! a7 i7 W限制返回记录的开始点skip() % p, q# t( Q  t* P
从第3条记录开始,返回5条记录(limit 3, 5)
3 L, L0 m6 @/ U% R8 f6 v
  1. db.users.find().skip(3).limit(5);   o$ {8 x9 j1 V  Z
复制代码

5 q3 C$ l1 u9 ?  _- x7 [$ g5 d查询记录条数count()
! n2 G# f0 H0 z) ^# U1 ddb.users.find().count();
: \4 }+ ^" F6 S" Jdb.users.find({age:18}).count();
" K. {: ^  V/ ?( ^  Q) s, A2 ]以下返回的不是5,而是user表中所有的记录数量
" w2 F1 p* q9 ]& q9 Zdb.users.find().skip(10).limit(5).count();
; X7 j/ A0 f) @7 B, ]# L9 |如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
! v6 K9 q* l6 |. K
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

' P# K/ W8 E7 @) Q: e( ]' N; w5 {# _1 N; T
分组group() : f3 L0 a" s5 i- k) u2 g
假设test表只有以下一条数据 ' ?) c% Q5 u8 m
  1. { domain: "www.mongodb.org" - `! k+ `1 Z3 l9 ~
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} 3 M  }+ @; z2 Y
  3. , response_time: 0.05 $ |( D3 V1 F( d
  4. , http_action: "GET /display/DOCS/Aggregation"
    ; n, e' Z: e; ~$ s2 X
  5. }
复制代码
5 Q3 v; q/ R) G/ s
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; 4 e; }% b/ S% Z. Z; m* y! i
  1. db.test.group( % \3 u) S- O* r  u9 O/ o5 k9 t& s
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    5 x. K  ~& B, U+ s0 D
  3. , key: {http_action: true}
    , g, `  O% x# Z) b+ [8 Y
  4. , initial: {count: 0, total_time:0}
    0 b% J6 h' L* Q. d' \+ c0 u
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }   \  U" a$ J9 m! n+ X/ b& C
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    $ _# i, N8 K- g, W
  7. } ); 9 @" h2 W+ y' `2 J' J0 w% U( n
  8. ' Q; `6 ~: P2 F+ ?  I' X2 @: [
  9. [ - q5 G9 \0 Y0 F/ A7 Y; Q+ n
  10. {
    " Z' k5 w/ L* l3 J6 w$ i
  11. "http_action" : "GET /display/DOCS/Aggregation", " r7 f, h4 {. Y% P3 o; m8 M/ l
  12. "count" : 1, ' T; v5 X1 X1 A) `2 k! n$ L
  13. "total_time" : 0.05, 0 A" d, y0 R% v. t9 ?
  14. "avg_time" : 0.05 . u6 o3 W% k/ f+ P  H' P& ]
  15. } ; _  x( o$ O1 ^
  16. ]
复制代码
( P* {& s, s) b0 d3 O6 Z3 x+ X
/ x" w" }* a: Y: d8 ?
/ ^+ m/ D6 |3 a1 e  y
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: \3 H+ ^3 E- A1 S% q
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

/ p# H% K3 L3 e. B2 b1 e0 x( r7 [+ g) ?9 e* v. Z

' p9 t$ F( |2 z
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct
    ! F) U9 ]2 e5 l2 r& y6 \0 ~1 S, d0 D, T; r
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
* o5 L) V3 s+ a1 P$ ^, O: c  Y2 m) H

2 z: t1 c: Q8 q2 K- H8 C8 a" S
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
- v7 V, L$ B9 W7 X; f

" b) ~( i& R/ i# w3 r2 }
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
  p' m3 C" p* v: E, h
3 ]5 u! o" g+ c. [* L; d0 u
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

# m& V2 h$ ?  V
  Y, W5 M+ @% ^7 T, Q
输出如:
  1.         
    ! c; A* h3 _$ i; M2 M1 [% v5 ?
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
9 c* M/ R) P" D! k; z% D

* W4 K1 q: e4 T7 R9 O
5 }0 _% b4 f5 ~8 [/ S/ |- \, t# a
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"  \; `* {' y$ \, \4 j" t7 {
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    / ?$ E' _4 N2 Z
  3.        xmlns:context="http://www.springframework.org/schema/context"
    $ `2 ]6 o1 s# S0 \0 q7 \1 r
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"/ a# o9 s9 `8 M8 P# |" P) ]
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans) v5 F+ ]7 V' I- T- G" O/ e1 g
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd( o6 `- O! Z' @
  7.           http://www.springframework.org/schema/context6 X7 i; l  {( G/ }5 v1 |6 u
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd; C; v' I1 L* T& C- J
  9.           http://www.springframework.org/schema/data/mongo0 x9 E" a9 p6 `8 W; V
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">: f, B" H+ {. v! h' W) o( d/ n8 W5 o

  11. 9 e7 w3 O4 e, z( H
  12.     <context:property-placeholder location="classpath:mongo.properties" />5 O% l: j9 p' h: E9 {1 c0 C: y

  13. ! f, ?! u0 P/ {$ h& G2 a
  14.     <!-- Default bean name is 'mongo' -->; x0 \* p6 E0 Q  r- t9 ?
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    : F* R# o( v  B. i) y

  16. . k2 h5 t  u9 d+ z. @% j
  17.     <mongo:db-factory id="mongoDbFactory"
    / a5 s7 T; O  |# [9 G+ W* B
  18.                   mongo-ref="mongo"
    : F4 j3 D& z" S
  19.                   dbname="mongotest" />
    7 P6 k# P. C2 u" n" y) l9 D
  20. : m5 x! k0 `# P
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">7 p% @# s: K+ o' R3 v
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>) C8 c1 c5 n& I
  23.     </bean>
    0 Y5 h( E9 A+ y
  24. </beans>
复制代码

3 P9 O/ a/ b% ~, {% y: s3 A

7 J$ s$ h# u+ C
maxmin的测试
  1. @Test7 v3 P2 L5 v6 P$ ?7 i! a% h( n
  2.     public void testMaxAndMinAge() throws Exception {( d0 h( s- e: U: w' D& u
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    . L3 t$ @6 T1 h% X1 s
  4.         Person result = mongoTemplate.findOne(q, Person.class);4 a  i8 g' O' \
  5.         log.info(result);
    2 K' j, h' h+ L1 \$ B2 ?
  6. & d. p+ P! c# I
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);7 a9 p' Y: \8 a6 d; A
  8.         result = mongoTemplate.findOne(q, Person.class);
    / Y! L1 l# h; N* n; O
  9.         log.info(result);
    8 E2 @0 f% v0 k3 k3 W9 D) \
  10.     }
复制代码

2 |* R+ h; ?" {3 n9 f4 Y
% t8 E& R6 j: u6 t- F
distinct的测试:
  1. @Test
    9 K7 ~+ E2 X2 Y
  2.     public void testDistinct() throws Exception {- d1 s0 N; ~; c$ G+ J0 O
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");0 n/ y' K9 I: ?: V0 l
  4.         for (Object o : result) {
    : |. |& h- C5 z( h, D! D
  5.             log.info(o);
    . h+ d6 H7 U: L: C2 U2 M* d
  6.         }
    . e6 C* z. h5 |+ D9 ^8 j

  7. 0 e# g5 l  j( [" H0 h0 L9 T" D) G/ C1 K
  8.         log.info("==================================================================");' o! d1 }) r+ O! R2 ?/ U
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    # J3 J/ E2 U% \- x
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());, {4 }/ a5 v( U2 o. M/ K/ m
  11.         for (Object o : result) {# K; c& A& M9 W% w, W
  12.             log.info(o);
    8 p% E2 q; Y: P: \8 v
  13.         }
    + i/ ^# D: {+ F7 _8 j" S

  14. , ^/ D! r2 R6 R; W0 M1 O
  15.         log.info("==================================================================");
    ( s8 P4 Y' I1 S$ }; _1 u
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    9 D) i" O0 x: J/ Q
  17.         for (Object o : result) {
    / K0 ~9 r% ^7 R* k1 h/ \$ T2 X
  18.             log.info(o);( Z( q4 i" j  m+ L$ H- q
  19.         }
    / u4 I0 |! X) e/ i
  20.     }
复制代码

1 [( p3 d2 L. U. s/ q* J# @5 C' ?# g
3 \% a0 c7 m: k6 j* E1 B: d
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    - t- o" R0 B/ w. N1 o" E! H# I  }4 f
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678/ [# B' e  d$ p
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    ; d1 B# ?  y5 U2 c! q
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654- F+ A5 B- f, m, S( R1 z
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    : e9 ]3 @) A- F% t. U7 o
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo. w* H- x. A1 s) j" A
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456/ d, r- n$ J" e  o/ g' n
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================% F9 w4 g: I' @  m; V
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 2345679 b2 T: h9 o/ g/ l
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    ! J+ y5 P! ^4 `5 |, n5 |! S
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
    . H' ?6 N0 m; R( h( h/ @! M
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876545 Q( \+ f) X' ~+ x7 M7 t6 [
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    / z1 O3 H9 O; a/ y; R0 {9 M* u
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa) n* L0 {) g6 V" B% C) ]; _: R
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    * z( E, C7 U* M! @  w& D2 `
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    7 I9 `) F" v5 ~! x9 c+ j$ p5 }
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www9 h2 W  ?* |. t9 S; i$ g  R: E! X
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    ( [3 }0 j; O! U3 S9 ]
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    ; N( x- _2 f0 n$ p0 _+ e
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    % M0 O1 U$ G, o1 G8 P  J( u, \% x" U
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr) h+ Z% m6 i' r! E7 p
  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
复制代码
! c, i  o' W0 l0 E$ n$ T6 B; w

: I+ w$ F2 w  ^0 H7 d* w; J( `
这里我要特别说明一下, 当使用了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 E) m* u) ^: a5 P1 v, u8 H7 q. j  n! [7 e; W# B/ j+ T
" x! F0 f* U( W  w* ]0 O+ j* Z
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-3 02:02 , Processed in 0.151403 second(s), 24 queries .

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