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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:
, z4 ~& ]$ T; Y" g( c  d/ j3 ~6 _3 i3 L* H+ ], p+ f
1 ) . 大于,小于,大于或等于,小于或等于
- I- C% P; P7 H2 }( o0 o7 N# w
" c  J' D1 g2 S$ J9 X$gt:大于
- B& s: }1 @' T3 G$lt:小于
" ]4 O$ t& n5 n' u. y6 x* g$gte:大于或等于" u6 l% H" i% n* l, ~
$lte:小于或等于
) \) v1 ~' \+ `: u+ ?1 Q+ Z: S2 ~
! \+ R( {( [  h* G6 k6 Y; }8 N4 @例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value
    $ t' e# l4 W3 U- Y3 _/ x% ]
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value' Y5 ?# ]3 q! |! h& K3 W
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    - {7 X1 H  G7 l6 P6 z! L  R
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

  v; w1 `8 F) k. v& O
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});, r1 ?0 I( d8 J. M, J. H- B- F
  2. db.things.find({j : {$gte: 4}});
复制代码
, n. _. l% I0 n# }. ?
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

5 f$ r# q$ j0 L, Y+ k" X4 }
, i$ r2 i' f) ?8 U9 {7 g. z4 {1 z  k
, ?- v8 m' w1 X8 ], g- v! {  P
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
& r( n) Y: T7 Z" L1 l0 E
3) in 和 not in ($in $nin)1 t( z" F! g0 I% H
' S" m& i- [* _( b1 `5 z8 }2 w4 [
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

* b9 Q+ z9 l2 C2 O0 a- [, l
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    # J7 @7 g) O/ Z7 _) \: @5 U
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

+ e6 U! ?4 [0 ^1 m2 B
4 O0 {5 d+ E- o4 I( B
4) 取模运算$mod7 r/ q. o; u( N% l
# k0 B9 s% m' \# T  O
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

/ a0 o  ^$ F1 ^% I3 u
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
% f, j2 w3 }0 O* b% x" C

7 A! ^8 o0 B5 l  j5)  $all
& U4 O- u/ P' P7 V! h8 K/ j3 d6 [
8 n% i! D0 [% ]7 [$all和$in类似,但是他需要匹配条件内所有的值:
9 R8 _9 N! l% k# R: m
; w) E$ N, P1 _7 d! `如有一个对象:
& t6 Y! H1 T' t5 ~9 x
  1. { a: [ 1, 2, 3 ] }
复制代码

! h3 A# o7 u0 ~% |- S# w# B  @# `
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
. W, v4 L) ^% h/ _4 w& p/ f
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
7 M: D3 Q0 z8 w/ _* ^
7 }& Q6 W/ \; C/ h
6)  $size
  w0 `; Q; U: }
1 d0 k8 C. k: h$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
% t0 q5 X% e8 ~, S- M( `
4 a' B$ h8 E4 r. K! J3 r下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码
9 F; g* o% K, p+ M9 _* q0 g9 ?% q
官网上说不能用来匹配一个范围内的元素,如果想找$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.

. H2 V+ h" N. }* R0 L
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
      A9 o+ [4 B0 v* U9 t  q% x
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

  ?8 ^& u; b( i; F
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string4 y% A5 @1 q* A) w
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
2 S0 K, c; Q( M/ e, j$ _
9)正则表达式7 N, K3 E# }7 l5 f- G2 g- q

) b) j1 @+ p5 ~/ N6 Xmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

5 B' D1 ]: V8 m; t' c1 B2 e
10)  查询数据内的值, E( n/ I! f, {0 c' x
6 N7 a- a9 `# A1 A$ l
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

; H) O- Y; T+ ]- ~* I9 q& o  J9 g$ i9 A  f
11) $elemMatch1 z1 o0 G0 \% W- q* n+ K% z
9 @3 K0 O) A% H2 W" H4 {
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 7 H' C; ]2 \3 ~* N+ d' `
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    ; }. k6 W# k( ^$ u- k+ z, `
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]3 `& Z% ]2 x# y5 H& H5 Z
  4. }
复制代码

0 W9 C$ p+ F9 x' z$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
& d% H! w" D5 x; u% m' B& a
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
2 l, I- Q9 [# Q1 A  S5 L$ O% Z  ?- s2 d& q% M0 X4 v! L" o
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码

* `" E5 s% ?# C3 U
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

& C. C; c; t& T5 k1 F9 z" w
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
; e; l3 i4 [( D/ z
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

( h+ w' ^- x! O, G6 S
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
* j9 `2 ?0 i4 A' Z- M" V( i* L& e# p6 V
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
: a! z6 i7 }8 q$ p% M
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );( ^- r6 a( g8 f- T9 `
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
! s1 d8 L1 Z+ [3 F5 Q& H+ _
mongodb还有很多函数可以用,如排序,统计等,请参考原文。2 s6 s! m7 z6 A

3 _+ Y9 E! [2 @5 I; g1 `4 ^mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:! f$ V' O9 Z0 U. ^/ i6 ~9 E
! k$ G& g# v8 U6 n
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions4 o" O3 |& e9 i. ^4 g; H2 w
' `: I) z* Z9 j( d6 Q/ {0 ^
版本二:9 ]- z( @( H, t
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

, I4 K2 A* M% g0 {' x5 Y; Y& `
  1. use admin
复制代码
5 V$ M! k" b0 \: s' l! u
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
4 }" }' ]9 @& X9 {+ l) d
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
1 I8 l2 I( F. u) J: a) S
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

0 b1 S) e5 ?# F
         5. #删除用户
  1.           db.removeUser('name')
复制代码
8 z$ M* K2 \9 \  w2 u  ^$ b
         6. #查看所有用户
  1.           show users
复制代码
: E2 r: h0 D' J
         7. #查看所有数据库
  1.           show dbs
复制代码
: X2 I- a, |7 T$ g
         8. #查看所有的collection
  1.           show collections
复制代码

% N' e& o' T3 q) Z  a, ?; E( [: J
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

$ e& S: G8 O$ Z9 m" s& J1 b% h
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

; D* O$ d9 O7 a$ g
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
; D; q" s+ y$ E
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

! r6 @& _# K+ h$ R5 r
        13. #查看profiling
  1.           show profile
复制代码
* Y' q  T& v$ C7 t/ f8 c8 X$ |
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
: X) b/ Z1 E: n4 ]* ?/ o
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

& l* U9 [2 R  [  |2 a
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

2 g! U6 h8 h# b; F- t
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
+ X8 G+ o* D6 q& I1 r
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

- |& `( Z5 d2 n) g: h$ C4 H
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

& g/ P5 {) h* u% v7 j
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码

/ J* y$ f" C2 s5 J- K
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码
4 G) u$ G( `: D. t3 K
   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 D% c  z& i) @; Z' _4 C# B2 s
6.  高级查询
条件操作符 ( r+ z; d5 U) y& s! y1 [
  1. $gt : > ! n- `" P3 S# C2 ~
  2. $lt : < " k% G- q; t4 w
  3. $gte: >= $ X( Q9 O- F* y/ d
  4. $lte: <= " K; r" [& z# L  ]
  5. $ne : !=、<>
    7 a0 e, Q  L6 B5 [* j$ }
  6. $in : in / h) X' R6 H0 |& o& k
  7. $nin: not in 2 b+ x6 [" A, ?- f% d
  8. $all: all
    ; R+ W8 x7 o- U7 O# g. r( w1 k* E
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
% e/ h4 C- ]3 Y' e" K
% W" [3 w$ K! S/ J) G2 F8 e! v" ~7 G
查询 name <> "bruce" and age >= 18 的数据 9 C. A6 t7 _8 ^. e" ]1 h. y2 L3 P0 R' a
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

, J3 @$ z# w# i
! ^8 I  R5 R& c' E1 k2 S6 N9 I( s查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
% Q4 o; q& [5 K& W3 t8 {
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
: d% t8 b% s7 }" G1 |( v/ X

& u3 M' p9 [" w- b+ {: }查询 age in (20,22,24,26) 的数据 5 e; F& K  G& Y( l
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码
5 V* [" i$ A* o
0 W8 o% M5 D* J) d/ P/ S
查询 age取模10等于0 的数据
  M9 i; r6 Z: G. Q# G$ N$ K
  1. db.users.find('this.age % 10 == 0');
复制代码
# O' t9 N1 V7 r( K( C
或者 + o- K9 g6 n0 k7 ?  {
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码
0 U% _, M# Y: L# Z+ S' }
- k4 x+ G; R/ m% i2 T# K
匹配所有
, M# {: o6 Y* f( U
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码

6 p% W: A4 u# a可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } ) ]- L$ \* B7 T) J/ k* s
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
& e- [' E0 |  v& C0 D" u' N4 B. L2 r9 ?
查询不匹配name=B*带头的记录 ' S, `' |; @9 @
  1. db.users.find({name: {$not: /^B.*/}});
复制代码
, |/ s: \5 C1 k/ W8 Z
查询 age取模10不等于0 的数据
( [$ b1 ~" [7 q2 _# [' D
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码

1 V/ Q( h: T' O! Q+ T( c4 S' ?
" y2 I& W2 u) M. J3 F1 o#返回部分字段
/ b0 o8 l/ T- d/ s) g7 ?9 D选择返回age和_id字段(_id字段总是会被返回)
& S$ J, i" g$ w" a" X
  1. db.users.find({}, {age:1}); 2 O( @" T, N: m$ L$ L1 f, i( u
  2. db.users.find({}, {age:3}); & C+ {! v: n# `. ~% ^+ X& \
  3. db.users.find({}, {age:true});
    6 w+ R) m7 e  }4 Z, e
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码

2 C. Q* S, y: O7 s& H6 g# n0为false, 非0为true
6 k5 e% C4 _7 C6 o" H+ o) M
1 j9 k( s, ?2 y- C5 t选择返回age、address和_id字段 0 K+ U. q* g/ E, N0 ~
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

) L, Z! v" a3 [' f1 u' i
9 B. `- L7 R1 r+ j( h* G: Z排除返回age、address和_id字段 - c6 e3 {7 T9 e3 P  d* L4 G
  1. db.users.find({}, {age:0, address:false}); , S1 Z+ X6 p, P$ m! d* b
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

2 T1 R2 ^5 \  A: k; ^' u1 r0 C3 J, s0 Z- C1 H* A4 C
数组元素个数判断
- U0 X1 I( J: D$ a对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
/ J, x- Z6 V4 p2 P( l7 O匹配db.users.find({favorite_number: {$size: 3}});
) u- A! W- j4 |2 z, H不匹配db.users.find({favorite_number: {$size: 2}}); , O! D; A) l- ~1 U0 [$ C

5 n3 `* ~" x# \. I$exists判断字段是否存在
- X9 T4 e- Y1 e查询所有存在name字段的记录 4 _( ]: z( K' q' z8 U: a
  1. db.users.find({name: {$exists: true}});
复制代码

' `! t) u8 ?* q8 Q! @+ y+ n" x查询所有不存在phone字段的记录
% s& \; `) P2 p6 ^
  1. db.users.find({phone: {$exists: false}});
复制代码
4 j, S. y) H3 {
$ _! M6 v% L# \$ @) E8 ]# m9 ]
$type判断字段类型
: s5 ~$ J% f# n/ t* `$ F6 }查询所有name字段是字符类型的 ; ~% j9 K6 J! v' q$ E, c2 t/ Y
  1. db.users.find({name: {$type: 2}}); ! v8 @: v0 z. P' K7 B$ L# x5 E
复制代码
& M3 n, W  L+ p& d
查询所有age字段是整型的
/ ?5 r+ N% z) S5 h2 B5 C
  1. db.users.find({age: {$type: 16}});
    8 m4 B, Q( z0 U1 s/ Z
复制代码
3 F5 `6 u. c6 p, w' l
对于字符字段,可以使用正则表达式 ! t2 g0 x) o9 Z7 ?! X% p( U
查询以字母b或者B带头的所有记录
( k! E4 t& R% G1 c- r8 p* _4 h
  1. db.users.find({name: /^b.*/i});
    ' i! d# j  T& }* u$ t
复制代码

; V% _) [! `; i$ H& `$elemMatch(1.3.1及以上版本)
: Z8 J: a, J# L) \$ T为数组的字段中匹配其中某个元素
) A$ U: h8 @8 Y& j8 [3 ~$ j# \+ \5 W: M0 {( |, H) Z( @4 o
Javascript查询和$where查询
  C$ Y# Y3 P; U% m查询 age > 18 的记录,以下查询都一样 ; }: Z" Y- k% w- A6 C+ O! h* L
  1. db.users.find({age: {$gt: 18}});
    + j, L6 G2 H6 f9 N
  2. db.users.find({$where: "this.age > 18"});
    ; {/ t5 g( s0 O0 ]+ v' o- |6 k
  3. db.users.find("this.age > 18");
    % |3 @( j9 ]5 l( j5 A  v1 E
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

8 A1 R% C# j. U+ ?7 L7 m0 W# z% m: |
排序sort()
+ g3 ~  i% g; B( _# w; Q$ F! W以年龄升序asc
) B* }/ r7 D. T% P# t
  1. db.users.find().sort({age: 1});
    . f- y: ~) Z; ^9 o. i
复制代码

; q& m1 _- {: k  A& V% \$ m以年龄降序desc 8 C2 ^# L( a7 V$ o6 B. }$ F
  1. db.users.find().sort({age: -1}); 2 C# j! X' A3 I' k$ @
复制代码

8 k" d2 f2 k1 \) R0 E& v' w' C限制返回记录数量limit() 5 J8 K& n7 z3 e- s* z* T6 t8 n3 y) D
返回5条记录 # M, G3 m* B: C' n3 Y
  1. db.users.find().limit(5); & q/ j+ n# a9 k* R% v
复制代码

$ S0 d8 f8 z- M  C, q3 h( M返回3条记录并打印信息 ' w: Q& R8 l( ?% f" C7 v
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});   S1 H6 a7 e4 R* l) o1 x; S7 C- `
复制代码
8 |5 @, x9 m/ S( ?
结果 * D3 g# r0 ~: W2 V4 e
  1. my age is 18
    # m9 v0 O9 m# z  j- z* G. K
  2. my age is 19
    % K1 E9 W! W: @" _0 S( z/ V# r
  3. my age is 20
复制代码

6 f8 z# @. T0 J$ y* N: ~; E7 ]) Q1 K; ?; z& G3 m2 M# h
限制返回记录的开始点skip()
4 F5 b7 G" g$ e) r( @( w) g" t从第3条记录开始,返回5条记录(limit 3, 5)
( F/ p2 _4 s7 t* a  }
  1. db.users.find().skip(3).limit(5); . ~- m& R1 G# H& D8 ]
复制代码
. l5 C! `! [, z1 Q/ U( ?- o) B
查询记录条数count()
$ E% P4 p& p) m- T& p$ [: ]db.users.find().count(); ) W% K+ x9 f% j* g! ?- e" [
db.users.find({age:18}).count(); - n& \3 I/ E. f$ s# e+ G0 b) _
以下返回的不是5,而是user表中所有的记录数量
- C/ }0 ]$ Q4 v7 ?' r8 C" A! D; wdb.users.find().skip(10).limit(5).count();
  t0 M6 d) _; @) W+ p% [8 r, b如果要返回限制之后的记录数量,要使用count(true)或者count(非0)   I0 m0 u' ~" w2 N, n
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
4 I4 }* Z0 C5 O1 I- Q

; e/ l9 z( \0 J) n& u( @分组group() 9 H5 v6 K  g: ^( |* g2 c! w  y/ C4 f
假设test表只有以下一条数据 ( N$ z9 ~4 {, L/ Q2 G& T! B
  1. { domain: "www.mongodb.org" % X; _5 P* X/ O2 o  _
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} 4 A' U8 o7 ]) N+ [
  3. , response_time: 0.05
    6 N* U/ }7 Z( p' v" S
  4. , http_action: "GET /display/DOCS/Aggregation"
    5 D  {3 p  `- ^
  5. }
复制代码
5 g" c* F3 [3 [, k
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; 6 h; ~! m+ k" ~' M
  1. db.test.group(
    ( h) s  p" s. ~/ y! \
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} . K  q4 _* \) b! j) @
  3. , key: {http_action: true}
    * f4 }" a$ `" o, A
  4. , initial: {count: 0, total_time:0} - r2 F" F: n( _8 B# x
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } : z# X! z2 Y1 o/ P# j1 c
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    8 G) ~; }2 l! N: T) n! s' [1 Z2 y' E
  7. } );
    ) d2 r$ ?& k( G$ e- w# S) p
  8. $ I1 p# l  L: b6 q" t) l
  9. [
    ) }9 x6 V0 X7 O& l+ W( D7 E
  10. { 3 k6 K6 n; z' ^+ x& j6 U
  11. "http_action" : "GET /display/DOCS/Aggregation",
    ; S2 @2 V( u( n- D3 Z0 u4 O  l& ]
  12. "count" : 1, ( n& Q1 _3 v# d+ Z/ |4 _# N
  13. "total_time" : 0.05, ! P2 @; o3 G! a+ C# g$ a
  14. "avg_time" : 0.05
    - c1 n- I; k/ Y; Z8 I! I" z" o$ h
  15. } . t; {$ G" @0 ]8 [
  16. ]
复制代码

7 T; J1 V5 U  n% l6 U: q. \* e! w, N) C, s9 p
8 C% d; B5 L1 u3 m  F: D
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
    5 ?. @5 y7 ~2 z
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

: g4 ~- Q4 P- w0 _6 j4 `
: N5 ?' b0 Z" E( v

4 a) U  z) M; C5 _- X* |
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
  • distinct/ \# L+ J3 C" U) y. B
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
, L& ?& K1 g- C7 q/ v. |
) b' x, ~4 d. u( V" z9 f% g/ B$ I% B
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
( L1 y1 S4 o; _/ A6 C/ I8 X8 @
  N/ u0 I- Y0 M7 D+ r8 E/ I
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
; w0 l, [2 S; p: p* j9 c8 f
3 B- l- H( L" i" A8 ?1 o' s( K* v
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
& L5 u# ]% _3 J* B+ ^& t- v
2 A4 \$ [' n8 C, x' x
输出如:
  1.         
    ( [5 I! {& X' k1 x! C" h
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
" L. l' m3 t# ?3 c$ m; d- R
8 D& l3 [1 V2 D: o9 B
3 t% ]* [" _* I# ]+ x
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"& o4 y% w# [7 g" D$ Y5 G( Q9 J
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    . P( v8 k6 `: x& V4 Y  d" d
  3.        xmlns:context="http://www.springframework.org/schema/context"
      d! C5 Z6 y9 J2 c' s. [
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"( ^$ H3 T  g3 p$ Z
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans2 V3 A" |5 X, z% M6 J
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    ; D1 b8 ]- d  z$ D
  7.           http://www.springframework.org/schema/context" b* [2 W5 B% `1 Z- ^3 Y" [3 N" b6 H( u
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd/ X% \5 j! c4 y6 @6 I$ @  ^
  9.           http://www.springframework.org/schema/data/mongo) S) c' a" ~" s3 N. D
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">2 Y! p0 L! T/ A! S" ^- t% Y6 n3 `5 M

  11. - u2 N  h6 E5 r" ~5 ~5 d
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    : X3 F  p' j5 K) B, D6 H: }0 ?! C
  13. ; u. U0 d2 o. B+ l1 `' V  R
  14.     <!-- Default bean name is 'mongo' -->+ y" M* t+ S7 @  f5 i
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    , B) S$ v- u- z  G

  16. ; L- ]# {  s& e( z  z
  17.     <mongo:db-factory id="mongoDbFactory"7 o8 ?2 m; s! b) t
  18.                   mongo-ref="mongo"
      {! w, ?2 l* c& h% P2 K% n2 i$ A
  19.                   dbname="mongotest" />0 N, ~6 }3 E, J

  20. # C: k" C% G0 _! ^, |
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    7 @4 s: T; D# k6 m% J" ^& c! w3 S7 E
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>; W9 ], j/ h: a
  23.     </bean>& b& O3 v/ R. q4 |- }0 @
  24. </beans>
复制代码
9 ?0 Y  e) \( [7 ], o4 w1 G: V

7 S7 e# A( b; {7 Y2 Z4 q  g
maxmin的测试
  1. @Test$ G  w' O$ F0 }
  2.     public void testMaxAndMinAge() throws Exception {
    . p% I8 a7 l( H$ r* l, g2 _% N
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);% `" z% g4 Z' U" v
  4.         Person result = mongoTemplate.findOne(q, Person.class);
    ( l; K' C2 U- [
  5.         log.info(result);. q2 ]2 o) T1 h# i/ h; h* h

  6. . R' h* i; t' m9 B0 L
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    2 Y+ E0 u5 g+ V7 O6 k8 ~
  8.         result = mongoTemplate.findOne(q, Person.class);
    : N! U- b$ E3 V3 l% q( E, y& h
  9.         log.info(result);
    6 n' C: s$ G( N& d8 M1 i
  10.     }
复制代码
% |# O5 r# M, m2 q" l- O

# ^  C1 [- z% i* p: @, B
distinct的测试:
  1. @Test7 z% e2 M- U, I* W* N7 {: a% h% `
  2.     public void testDistinct() throws Exception {+ a' ~0 ?1 j$ u, ^1 ?
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    - ~2 h6 G  M5 E- F& P
  4.         for (Object o : result) {9 B4 O4 N" D7 M1 Z5 R
  5.             log.info(o);0 a2 F, C/ x/ y1 @+ J
  6.         }# x5 S" Z- M3 ?8 S+ ?4 ~1 l
  7. ; U* ?2 Y2 o8 d1 H
  8.         log.info("==================================================================");
    4 V0 T8 ], T8 z0 V% Y! m* e
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));1 M8 _+ j9 S" M' B' W
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());( @2 i$ a( R: z5 ~& B6 D
  11.         for (Object o : result) {6 W/ {% F( S4 S) i$ n7 G, T0 x' Q
  12.             log.info(o);
    $ P" ^5 @5 c# e  G5 p$ G
  13.         }
    ( P5 W6 p; r/ `

  14. 0 j- F' Q6 t( K
  15.         log.info("==================================================================");) ^; c$ r* R2 B/ W+ d0 G, G% ], F9 M
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
    / e  e9 z+ c9 h9 C1 C5 V1 L
  17.         for (Object o : result) {
    6 l; R- m" e4 k: U2 @0 e3 L( d
  18.             log.info(o);- W. W/ p: \! V$ r
  19.         }
    4 j2 c, a1 x1 t4 i) j1 u% X7 `* ~
  20.     }
复制代码
; Z" q1 X/ |' F+ t) ~7 S
' h4 a* ?# C; v( A
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    7 H# k+ ~( k' R' M  E$ v& ?
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    8 V+ l8 s" F9 `2 Y- R9 ?
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 4567890 U* D7 Q; w; Y  X0 v$ f- O
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 9876541 k' ^; Z+ i% @. }
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni/ }5 `. ]* X" i; d' a. `
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo8 F' q1 i* u+ z) ?
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    / ]' {2 u+ g" Y
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    4 c$ p  `# w' A6 g% W8 m. u3 l
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    4 a$ H7 ^% i1 \$ z
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    % j. m1 X0 E1 f: U3 P. u( M  ~
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 4567893 ~+ @- i1 L* D1 a/ M
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    7 n' l3 s( Y0 d9 t8 c
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    # J& N# g! t6 p# A" Q
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    ( n. o# K: R/ t% _4 u" x
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb6 U0 V/ ]4 F9 W! C) b
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    3 @8 q4 D0 C/ y3 c9 I! w8 ?
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    8 d/ J' X8 o; Y$ K
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    3 Y0 a* }# i/ n( K5 @  m
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy1 W+ {4 k% l9 P, q. O* |* e
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    ) v$ C; b) y! a) c
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr& g( _* D+ H: G3 ^: N- {
  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
复制代码
8 F6 Y* i6 D3 R0 G! B

: i% z9 u- A# }# X$ j  u
这里我要特别说明一下, 当使用了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等信息。

. _) k+ g" D! R3 F; l
) P3 ?6 h7 L  s$ ]8 J5 F. u
: h7 P  r( @9 z% w* ^9 q* b0 T
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

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

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