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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:. S( k5 _' @7 T- g! j, J
( M6 ~$ e0 r- V- F7 x$ C: G% L6 i
1 ) . 大于,小于,大于或等于,小于或等于6 ?+ b+ G  n2 g4 n, }1 a
# {" L3 ^& z: J2 g& B8 h
$gt:大于2 x9 z4 i5 D+ v; i
$lt:小于
- G( A* d$ L, u( w0 h7 z! Z& W; v$gte:大于或等于, A! \) g. g' |% J
$lte:小于或等于
8 |7 i! `6 o" N7 d. \! H- B3 |# f- a4 y9 _$ m/ `5 ~0 h  y
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value7 p# x5 K, l% g& k+ I% `
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    $ I$ c* a- X. E( G
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value  c7 }3 M/ f# J% b+ ~
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

8 [, @- f$ ]* o) L1 n. G1 E3 Y+ X/ u
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});% U7 X7 B$ `! ~: D# j- c" D
  2. db.things.find({j : {$gte: 4}});
复制代码

3 T; }/ U2 r! h* ?5 Q; I) S
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

! Q2 a: O; P7 f  X. I
/ R, ]3 n: B2 Y, Q, G4 D) W% y
/ c( _& m% v2 O: R! L* F
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

3 k. \# ]) O: l1 m7 F; M4 B% `
3) in 和 not in ($in $nin)- d; u8 M4 ^; x$ o+ Q
2 a# v0 W! E! ~- `& j
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

, `6 O  m) g5 u- O3 u8 {! q
例子:
  1. db.things.find({j:{$in: [2,4,6]}});0 r! A7 {$ `: n- s3 Z
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
, X4 y; l: Z! |1 n$ y
3 M  ?8 T. ?9 p4 t1 c/ l! P
4) 取模运算$mod3 A8 G8 R! z" X" E* u# p* _; i" p
: p) f, c3 X: `8 f) J1 G( _
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

4 t3 |( ~# `  r+ A3 r/ i
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

4 V# n( n# s/ H, |* {) D! i

2 v0 p# g4 f# y5)  $all  T  D, A  f! q+ X0 X* ^

: V. C: Z" k4 v. S& C$all和$in类似,但是他需要匹配条件内所有的值:9 S; H9 p( F% A

, i! n$ T/ R9 I' J6 B+ E如有一个对象:2 A* E4 N' R9 j" _5 G6 g# n
  1. { a: [ 1, 2, 3 ] }
复制代码

! c5 S% @6 L8 n( s" y
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

9 [  k2 d8 o. N  y6 ?; ^
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

$ H1 {0 c# |! j! w" {- h
/ F' `: Y# [/ |4 \! W
6)  $size
. x9 b9 a4 Y/ @( J8 ]
. r, G0 s+ {+ D. e& b0 ^) Y$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
2 s4 d% p0 D/ |: G6 z- b/ \' I) f& B( J6 @7 W/ }! k
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
) w, g7 q# _# n  N, y8 j/ g4 Z
官网上说不能用来匹配一个范围内的元素,如果想找$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.
' q& M& J2 I* A# e& D( K1 p4 D  E
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
    2 @; l0 m: L9 N+ ?4 X
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

8 ~- l$ _# Z; {
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string9 ^9 C- ~; b' i
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

+ A) [  F4 Z2 G5 T8 k
9)正则表达式
+ }% V' S, _- r& h  _; F3 d) U% D# w- q5 D' }- O, R
mongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
5 j; j( w8 Q/ ~, L  H% M: r
10)  查询数据内的值& n2 ^- s2 g. ?
! m! b* [- a8 `. ]. |9 ?. j2 I
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
  U2 d, L8 G, n. [4 ]3 ]; ]7 l
11) $elemMatch
( E4 ^7 N+ `3 O/ \1 S7 `8 [  {
8 ]- {6 q3 Q5 A$ A如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    2 b# Q6 I3 }% e2 f/ R5 m. a
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    + G, r1 k) r) ^% W6 `' j
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]2 r! I# L5 R4 z8 P
  4. }
复制代码
3 w: N1 L  B! o4 e; L1 U
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )! p2 m0 {' t' {! z: }; M# c5 R2 M
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 3 w, r; X6 c. L7 t3 s0 r
5 ^& e" K; k- F
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码

' z6 i' @; S# L* q9 y) v* k" {& T) z
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

; J' Y  e9 S# g5 X
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
$ ~1 d% {) a+ N) E4 C
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

, j8 ]  P, V- w2 A& Z- b$ [
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

+ Q* Z* ^8 f/ k! x1 g+ L4 c4 _1 c
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
  h& p$ q- C7 K. g# t0 G; J
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );( ]7 N$ X4 P9 Y4 Q; h! ?" e9 n. b( L- W
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
, o5 X0 O) g6 a- s: x$ s
mongodb还有很多函数可以用,如排序,统计等,请参考原文。/ U% \/ M" V, X" a

$ D- u0 F; @6 n; z5 q0 j  V) }; e3 Cmongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:
! @. a" s5 @4 ?) N" q5 }+ `3 L' y, q+ x
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions9 f8 E0 t( e# q/ u5 Q

. c0 C9 N/ E2 x0 t版本二:# L9 }! W% g$ b8 u: Y- {
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

5 ]8 n/ D3 t, `2 g1 F
  1. use admin
复制代码

  b! N0 X* N0 O, F8 K$ x) f7 L
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
6 M9 N) I7 u7 u/ F
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

; g+ I+ Z& f( I% z9 c) \; B2 `2 U) }
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
3 r" n% t* J$ y" J* v+ A  r
         5. #删除用户
  1.           db.removeUser('name')
复制代码
7 W/ [- n! i+ D( q8 J0 R2 V2 ~
         6. #查看所有用户
  1.           show users
复制代码
) F1 `+ y3 Z% A2 k
         7. #查看所有数据库
  1.           show dbs
复制代码

5 f& l) b8 e; O
         8. #查看所有的collection
  1.           show collections
复制代码
9 x- j4 l" O6 I. S3 x6 h
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

6 e" Q8 j  m, R2 J+ d
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

0 ~. Y3 ?/ ~( j( e/ ^* {
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

! g& ]( _) u+ r6 L$ v8 O
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

* [1 s4 O. ^  d" |& b6 R# ~8 A
        13. #查看profiling
  1.           show profile
复制代码

% Y- r8 ~1 t4 p! l3 I4 J2 Y
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
  K+ n( b# N# U( b3 k) o
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

" C& n+ d% H( L8 W3 s' I8 L8 h7 i! Q
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
' F: J* K- t6 }  Y8 n: H8 M4 S
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
8 I& W8 w- H3 ]9 H* o8 r
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
$ z5 O9 d" F3 O* H
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
4 R: {3 e$ s$ C7 o5 |% K! M. D
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码
% O# @1 e1 K- t" N0 h% z" L
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
; b1 x. {# D, _+ V( 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()
# a  d$ Q3 \2 [% c* d
6.  高级查询
条件操作符
. U6 E6 d# a9 |2 I( E
  1. $gt : > # u2 c, Z) [' l# ~/ G& d! F0 h
  2. $lt : < . c6 ?1 g( p" [, i5 t0 k) O2 z( \4 H3 @: @
  3. $gte: >= 4 k+ a; t. v. |' S. |
  4. $lte: <= / x9 d5 ^9 P9 t- a1 W) Q. `
  5. $ne : !=、<>
    7 ?! F9 s4 T4 f1 d1 y' b
  6. $in : in
    % N, P1 U. N( W/ u1 h2 B
  7. $nin: not in 6 m6 t2 w5 y8 o" x6 p
  8. $all: all : Y" I7 j- h- @
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

9 U9 ]* o- K: }: S
8 l2 F9 Q& o7 J! [0 m4 X  Y查询 name <> "bruce" and age >= 18 的数据 : o1 A( E9 u5 o! z6 A/ `; @2 D
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

- V& T4 ?9 M" j7 U5 C' C3 F) b0 @# L2 M  P% X* H5 |
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 3 j' v) ~' ]+ R& f1 v( W
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
. T" n3 g7 u! B( E# [: |
% [4 K! X, j7 w+ J2 v! \; g
查询 age in (20,22,24,26) 的数据 $ p; z2 x! W6 o# k9 i& _, Y6 @/ @
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码
* E  E+ U) h/ s4 T: Q. \
" l8 s& E5 ?( t
查询 age取模10等于0 的数据 ' X) t2 |6 o* n1 j" F. Z, m
  1. db.users.find('this.age % 10 == 0');
复制代码
/ h, S# s9 o& r# `# }& Y7 ]( N3 {: w
或者 ! L, D: v, H$ |+ t& X
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
) B+ e' [) B) e$ x1 L& O- e- n4 Z
! t# y" e) P  }7 R% p- S2 D
匹配所有 7 L- h1 l- Q7 [
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
& Q. ]- W- O" t! W7 T
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 6 ?1 x& S( f7 D) _! I
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
' [& w4 ?2 ~* ^1 N# ~: F9 i( _" z+ N) u8 m: x/ D  C
查询不匹配name=B*带头的记录
! p$ v4 k7 Y* F) t
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

( S( r# u$ ]0 ~3 u. R8 C查询 age取模10不等于0 的数据 ; r' q3 Q3 u) g! l: e
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

! }, q* `* M+ n7 y* j/ v, ^/ X% N
* D4 j7 _5 r: \$ y  g6 Y#返回部分字段 7 f' @# S  R0 b
选择返回age和_id字段(_id字段总是会被返回)
3 j) x6 G3 \9 I% p, J6 K
  1. db.users.find({}, {age:1}); $ W- V7 ~( M$ l( l( f+ V
  2. db.users.find({}, {age:3}); / I: N6 W+ H8 Y. G
  3. db.users.find({}, {age:true}); ' S. a( S' p1 D8 V  T1 Z' X. N
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码

! p5 y0 t$ Q; |  ?& P, R# O1 r9 _0为false, 非0为true 7 G, h) m4 s3 b* F0 P! g8 [
. d- K1 v) `( a; q5 S% U0 j. A, V
选择返回age、address和_id字段
2 a: t2 O4 `5 `8 V* }% K2 w
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
% M% m1 E5 u" P0 Q5 }# a! {( a

% L# c- X" r  z# _1 N! d4 F9 d; G$ W排除返回age、address和_id字段
7 U+ L' q7 u: C5 ]: e% G
  1. db.users.find({}, {age:0, address:false});
    ! P( s: V) ]; C  i9 Q0 D# W7 a, i
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
# T  ^' v5 b' S2 @

" w6 _4 ^& d+ W& d数组元素个数判断
7 j2 C% Y$ O* @" D( T对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 # m# M: A$ P3 T6 I& G0 ^& G
匹配db.users.find({favorite_number: {$size: 3}});
. p8 A4 y4 n4 c* }3 H; i! T不匹配db.users.find({favorite_number: {$size: 2}});
( o; m0 Q# q, [! s4 {2 v! Z  q& U5 S8 g0 p) G( U+ Y* H  o3 D* ~" h1 o
$exists判断字段是否存在 ; l) E3 ]" K9 Z1 B- [
查询所有存在name字段的记录 & P/ Z1 W  Q6 f8 W
  1. db.users.find({name: {$exists: true}});
复制代码
* I8 {5 S7 ]- s, l
查询所有不存在phone字段的记录 0 \8 E' P' X( H; G
  1. db.users.find({phone: {$exists: false}});
复制代码

) A$ I" w3 ?. Y
  N4 s- z, V) n6 A; {6 J( f6 L( @. m$type判断字段类型 4 q, d, M( f, ]1 I+ I7 X
查询所有name字段是字符类型的 " V6 M* }- D9 s5 T$ n0 C6 u2 [- U
  1. db.users.find({name: {$type: 2}}); 9 o1 ?  S( I! r
复制代码

% ^2 C7 M/ |9 u8 j查询所有age字段是整型的 8 \/ Z+ _3 w, a* f* ~- J: H
  1. db.users.find({age: {$type: 16}});
    . X( j& p9 G6 R0 `- ?7 M
复制代码
8 L0 z' g, T- v
对于字符字段,可以使用正则表达式 4 c& \6 H. R# f' j# w
查询以字母b或者B带头的所有记录 % U! P( E0 J4 E7 B( S6 I+ y
  1. db.users.find({name: /^b.*/i}); ' |( _; y) j% ~% b0 F$ K
复制代码
/ z6 e' ~( m9 u* M* y5 A1 V
$elemMatch(1.3.1及以上版本)
* s6 b  V, L8 ~9 ^为数组的字段中匹配其中某个元素
! X" I* V* \1 C7 ]; q6 Q; S: K& d* z. @
Javascript查询和$where查询
6 v; D( S* u7 ^) i% K* b查询 age > 18 的记录,以下查询都一样 6 S/ \3 h) r6 ?# `3 a: o2 @
  1. db.users.find({age: {$gt: 18}});
    3 q5 `+ C& A5 ?2 u% y4 Y6 X
  2. db.users.find({$where: "this.age > 18"}); * j6 i3 H/ M3 n6 w) f/ K- p1 ~
  3. db.users.find("this.age > 18"); ! ?& Q3 F; Y# G0 _& g
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
- T! e6 u1 d: y" K9 ~$ q
+ B8 l- S+ d9 ^# N5 W, W) O
排序sort() - q3 c+ U- M4 S
以年龄升序asc 8 g' P9 U* l( t4 B& R8 r7 q8 s
  1. db.users.find().sort({age: 1}); : K4 E  g$ l( n  O- Y( d- D, A
复制代码

% Z/ F5 X# g/ i0 ^0 b以年龄降序desc 6 g" j# p" |7 E' G9 O: g# U% X
  1. db.users.find().sort({age: -1}); / T! q; V( m  ~# x: G3 w. G$ p
复制代码
7 n- v4 U% v+ F( R( [( m
限制返回记录数量limit()
& b# X' _8 L+ M0 G3 y返回5条记录
0 A9 _- _$ U  t* i. Q
  1. db.users.find().limit(5); ! H2 b! |7 O+ T( L2 e
复制代码
: [7 E3 i9 Q* m9 Y" _
返回3条记录并打印信息 3 l& D& P) l/ B/ @% N' e
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); & D$ g8 ?0 N( k1 k: K$ H
复制代码
% _5 u+ |! Y6 c8 L
结果 , g+ t8 Y  g: b( T, y# a
  1. my age is 18
    / t, V& g2 z- ]
  2. my age is 19
    8 Z$ E5 M- q  w3 G  b4 L, o. g+ O- V
  3. my age is 20
复制代码

) d8 R9 t0 R4 f2 C. |
. F( L5 a) ]: I0 E$ X限制返回记录的开始点skip() * w5 t5 X( C8 ~5 i3 u7 V
从第3条记录开始,返回5条记录(limit 3, 5)
& Z& s' H6 ]7 }6 x
  1. db.users.find().skip(3).limit(5); 2 n% s& G" C$ g
复制代码
# k9 C- s/ Z! w7 h& o7 e, {4 l( f
查询记录条数count() 4 Q2 U$ u8 o( F) M
db.users.find().count();   B3 j( C! p4 B! N9 j" _1 B
db.users.find({age:18}).count();
% |* p! p" R( t6 Y以下返回的不是5,而是user表中所有的记录数量
, k! K) t  W1 O7 e$ S8 pdb.users.find().skip(10).limit(5).count();
8 r; L9 ~8 F: y* K" |" L+ g+ i6 h如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
3 M5 \; {6 O" c) I: i5 z! N
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
9 F* N- d& ?- _7 e
- n' [  c: a$ {) ^, o- n9 W
分组group()
/ c. Z$ [4 V6 E  @" w假设test表只有以下一条数据 : O& Q, [! i) H4 U# w
  1. { domain: "www.mongodb.org" 3 P& i; F3 c0 F& ?5 h9 Q
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} ' l% p: p# E5 C) q, ?$ x6 U
  3. , response_time: 0.05   y  ?/ c; X0 v2 e% E) ?. ^
  4. , http_action: "GET /display/DOCS/Aggregation"
    + U/ B2 E6 `% J/ r# G' k' H
  5. }
复制代码
- l5 C" d: R! n; ^' h
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; ; {% b/ j% f- P3 N% R/ ~2 ?. ^
  1. db.test.group( " l' ^, }4 ]# S
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} & i) }: U) r9 {
  3. , key: {http_action: true}
    : a$ s% n$ S% r/ J5 I
  4. , initial: {count: 0, total_time:0} ) q+ W0 D; t# R
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 9 P5 K& ?* T! T+ B
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    . Y, ?0 X3 X  v* t# X: [/ @+ J
  7. } );
    * r! X; ]/ Z2 M$ B- |

  8. 2 U0 B$ \5 \* U! Y) T( n/ [2 j9 Z
  9. [
    8 Y7 _4 }- x$ w( c1 t
  10. {
      T; D; a7 W6 |: H, ]* X
  11. "http_action" : "GET /display/DOCS/Aggregation",
    5 M/ @( {* F# _# U
  12. "count" : 1, ) ?9 x: P  ^2 E6 `  M
  13. "total_time" : 0.05, # G$ \+ W& e  Y6 p8 a
  14. "avg_time" : 0.05 / _, k6 |: O* ~2 P) ^
  15. } 6 F" p# x( x* X9 }( K3 _& X
  16. ]
复制代码
2 {8 O8 p! t7 N+ l8 L  B6 {$ d
& t' y% I/ f, S2 k/ j

) E* x* |# e; YMongoDB 高级聚合查询
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% L2 l7 I) ?7 ?" O- u- x7 m$ R0 M
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

* o% [8 v( V, g& I2 Y4 R, t0 i' ^8 ^, V" V( ]  G! q1 E
& f, Q1 F' N/ C# s: \
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct6 r* [% A1 \" ^0 ^7 ?0 Q
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码

: x3 \+ p! V* a- _5 o* {" O; b5 A3 y7 V/ e
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码

, K8 y* _! j; c$ `/ g8 N3 L' m+ Y  y9 Q6 _- o/ h* V
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

+ B& o4 L2 G# @( E' @0 B% O! K2 |  o
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
/ [) t' n/ P$ u

9 O1 e# C2 ^- }  s+ H* o
输出如:
  1.         
    1 Q# Z  @! n5 J$ E
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

) _. x; ~1 j2 K
- B; p. d. r/ G% r* b# A6 V; f& v( n, x  L0 G7 p
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"; X, T. H( Y9 c, B* U5 N  D! g
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"7 A& h8 ]- Q3 W" v* J
  3.        xmlns:context="http://www.springframework.org/schema/context"8 q" {  o) a: e2 l# p
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    2 c' {; O' F9 W: }
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans( D: y7 H/ c& N1 p! g+ x! C
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    8 q/ D( t& r+ N( C  N
  7.           http://www.springframework.org/schema/context
    + [2 y2 P& R6 _" a# C
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd' F7 d" n9 R1 O
  9.           http://www.springframework.org/schema/data/mongo5 }9 k/ i7 e5 X& v4 h
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    $ ~. L' J+ B( x* T5 h7 B: e4 ?

  11. ! x6 K) N& b; q! U* f. ]3 K
  12.     <context:property-placeholder location="classpath:mongo.properties" />% ~7 r; U. K/ s9 ]% F
  13. 4 y5 T3 R6 I4 ^2 v" h
  14.     <!-- Default bean name is 'mongo' --># f# c) N( s& w: v  l9 g* \
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    " v5 }0 {/ v& t- ?# A
  16. ' a) z: Y* K# M3 n5 Q) H4 d  C7 K# o
  17.     <mongo:db-factory id="mongoDbFactory"$ D; ]+ {6 r+ X/ T6 }9 L6 D* w
  18.                   mongo-ref="mongo"
    . n  O. ?8 h" K! [5 s) @9 Z2 Q
  19.                   dbname="mongotest" />4 I7 t$ i* h2 p" |) E$ }

  20. $ |7 C  m' v+ C0 @1 t/ {1 k6 W' u
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    ! i- W3 e& c/ J
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    3 ]# q4 A- K3 q* D0 m' X
  23.     </bean>1 \2 z0 }2 w' x" ?
  24. </beans>
复制代码
+ h. ^4 Q- r6 }; f4 A

9 M* }' L$ i- D9 F
maxmin的测试
  1. @Test: w: T! o3 f3 _$ M1 m
  2.     public void testMaxAndMinAge() throws Exception {
    ! ?7 Q# b5 h7 j/ u( R, c! {3 q
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);" o8 d( p/ b+ S& p$ E7 O
  4.         Person result = mongoTemplate.findOne(q, Person.class);- }* e  U8 S# x* l
  5.         log.info(result);
    7 Y* \! l1 {/ F  y7 h: m5 [* \
  6. 4 I& \' F6 E( A9 Y* x7 c2 [3 ^. o
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    - a# v1 n% h$ I; u" N  h
  8.         result = mongoTemplate.findOne(q, Person.class);' u, m: x- [0 t/ f" h
  9.         log.info(result);
    " p, c# ?: H( I5 g& E, {, w
  10.     }
复制代码

, `/ S2 H$ h8 W' h1 W" t7 Z! a2 M" u+ j* f: x8 b
distinct的测试:
  1. @Test" T  f/ x+ A# I
  2.     public void testDistinct() throws Exception {
    5 F( c: v- r: x' @+ M( M, m
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");. ]  v) ~" r( r' {3 u( ^8 }: ~
  4.         for (Object o : result) {
    2 C5 H  F5 H+ @& l6 p$ ~
  5.             log.info(o);- p) N; K6 F% r* F( f+ f( Z
  6.         }
    7 i+ C6 x/ ^( D1 y$ B1 v" V( r
  7. 3 a( ?5 H6 N2 i. J3 {
  8.         log.info("==================================================================");
    6 w( N3 T! w/ D( Q6 Y
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    6 j" B3 b1 s; l$ B  b" u9 ^
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
      U8 V8 ~3 T5 ]1 g  _) ^* p1 \
  11.         for (Object o : result) {
      J$ t2 F: _; e- [  Q, M
  12.             log.info(o);
    * I2 D! N2 k9 _' p6 A2 K* `7 H" o/ P
  13.         }
    3 s& r: u0 h" n. W
  14. 5 l3 @6 f/ M5 P- A9 N5 s
  15.         log.info("==================================================================");
    4 C1 b' ^! E3 e7 y  a
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    ' @( d3 |1 |; V# X
  17.         for (Object o : result) {) U# B5 F3 F1 j# n, [
  18.             log.info(o);+ n2 U# P" S0 f; ?
  19.         }9 R6 H2 A$ y* D) Z8 O: {) A2 F" H
  20.     }
复制代码

* p) I* _9 y8 N. m7 f2 b. j# ]7 E8 O* e- Z; E0 w# @
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 2345679 [$ p. e5 ^) t" |
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678. u/ C7 _* O$ x. n: |/ _4 g8 B
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
    & f5 u  _* l3 V# c* k$ T
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
    6 B9 w, `; j. ]0 p
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni: v" U3 H: Z- s7 F
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo. [. ^; J: q3 r: F4 v
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    - g& Q6 _9 t& ]$ X; L7 b
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    . P$ O3 Y- c) ]4 {5 r* ]8 k
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567; r1 O4 `/ L+ M! j" o/ ^
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678! z8 J6 g8 U7 @. Z# Z' B
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789& J3 {! Q1 Y& I- X* G
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876540 E, v5 z9 j4 r! |- M  Y
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================7 ]. U* G, ^4 N1 p# x( A1 U
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa( g/ {$ J; J: Y& u9 _1 w
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb4 T) @5 K" E6 l6 i' X
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    * `+ K$ |5 ^& C; W7 a
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    + Y& c' j. N! x2 F* o6 C, e
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    % J& f/ `+ w3 m, M/ z
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy0 p# _1 r; L  G! `5 q
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz. U- j* a" H0 i- }
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr8 G# I+ D# V4 i3 z- l( r( r
  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
复制代码
0 Y2 i4 W0 k' C0 O2 v
/ W4 x, C, i. G: J' N! r+ ?' E
这里我要特别说明一下, 当使用了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等信息。
. T- x' L1 ^; s5 E+ v
* o" f; L5 ], g$ Q2 V/ H. m
& b# Q6 m$ y: {4 q: ]* r- g4 i
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2024-5-19 22:26 , Processed in 0.154157 second(s), 24 queries .

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