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

QQ登录

只需一步,快速开始

 找回密码
 立即注册

QQ登录

只需一步,快速开始

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

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

[复制链接]
跳转到指定楼层
楼主
发表于 2019-7-4 17:21:36 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
版本一:
$ l' J( U8 l6 h2 |  e/ f: ^* ]. F) X
1 ) . 大于,小于,大于或等于,小于或等于3 E6 K& X( Z+ w! `5 A) L5 Y  i' ^

% ^" \7 H: z- {$ i2 z. l* O$gt:大于
3 w. H; b2 j* R% j2 C+ X$lt:小于
$ z& u( D0 [% C( \5 [$gte:大于或等于( H$ P9 j3 j2 a+ Z! l: v) b- _1 x
$lte:小于或等于# E! v, v) C6 a+ `" m# `& v
0 M6 l) P# y' L- ?9 c
例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value3 R/ N" t5 \9 J% |8 I
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    9 g, g$ A9 s5 {1 s
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    . a, t5 h# Y2 V1 I
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

+ t4 N& d7 R$ j; d) I
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});3 D% M$ }. J2 v5 l
  2. db.things.find({j : {$gte: 4}});
复制代码
; k1 I) F( F  |4 U. A% d
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码
$ S+ W! j6 A( S( ^
) Z& @8 c# \6 S9 l9 X0 [
0 R/ S; Q( u8 R2 v" h- F
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码

+ X4 P% h9 U$ h! O0 k: _
3) in 和 not in ($in $nin)) o8 G, {% k' x$ {2 r6 c5 u! c
6 X- ^3 u3 p9 c4 `& P6 q1 k
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

/ t) u# ^3 J/ A& g4 v, I. Y, P
例子:
  1. db.things.find({j:{$in: [2,4,6]}});
    ; [0 Y* \" q* K# @7 O4 \$ y( O' u
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
" t7 N) h1 S" x. t# P6 t3 {/ t

+ X- L+ z' \. w# A7 M1 |- ?( C4) 取模运算$mod
: i: x: M0 Y2 ^
9 [: x7 \6 p7 y6 ^3 e; Y如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

6 U& c; v* H- Q8 ~4 t
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

5 d. `  L7 i) j0 i

' y; x9 A, i9 C5)  $all
0 k" S6 S; f8 d$ _. v- }% m0 }9 |  s; P+ n
$all和$in类似,但是他需要匹配条件内所有的值:
" f' |$ q# Z! Y
7 T. G7 y7 y) @5 Y如有一个对象:4 `  [; `  L/ `+ E
  1. { a: [ 1, 2, 3 ] }
复制代码
2 R, M+ H; E, o7 C7 B$ u
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

9 y5 f( `2 E2 D* O
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
9 g8 J' E6 k/ U( }& t& m" D6 [! [: P

- @1 P& L" {9 J5 x; i- q" m8 m+ k6)  $size! K4 T" P2 b6 V" ^8 Z

+ N0 {9 o; I; E) [! A+ N; J0 W$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
4 j5 V8 j4 S5 p: Q% c2 z6 P: ^3 F" I7 w+ f: x# u" \
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

: [3 p4 ~; {! `; e* l( y
官网上说不能用来匹配一个范围内的元素,如果想找$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! \  `' L% T& q  ]) ~: [% e
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回+ S8 o6 Q+ _4 s' ?2 r9 K
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
! z6 z# R2 h! I5 l2 n# n( m4 B
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    * m) F, U; F- q8 `: _
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
" y4 d8 K: t# ^+ ?0 U5 U5 A( F2 n
9)正则表达式+ j  }: u& n2 I2 S! w

4 z/ Y; A% u1 l; lmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

* f" c: S1 L% v8 p6 D
10)  查询数据内的值
& f/ B6 |, P8 d* c5 @& H
% Y; \) p& |* {- k1 E2 |/ e下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
1 s+ s! H% @5 l. i% @$ a
11) $elemMatch6 u& O% I6 t) [4 i2 L. D
* S' t. Z  t# M1 L9 Y0 ?
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) ) s5 ^! s) u% J7 L, W
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    " T( K( M3 N8 R! V7 \, R
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ], [2 N. C. A6 c& P
  4. }
复制代码

, ^* \  A' c+ x" ~9 J+ c- k! w$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )! r& ~: ^! i3 F: [7 y
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } # S3 E, X4 c9 M- T; U1 D
' `9 y1 Q. [6 U( ]* G( F& ]
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
" Z7 q6 [5 l. o9 O
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

9 ?5 a+ G+ H9 r) k
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码

( D. _; b2 n' x6 v3 s1 x
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

" Y1 q2 [: D" T1 b
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
% D  ]: j1 |: v5 ~" C5 C' g
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
! q  Q! i& g8 ?+ z9 }
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );* U! J* A4 k5 G9 ]
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

( T) {3 d1 [, B$ o
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
% P- L$ J* a' K& K' l* L5 p" ~9 u
8 K& B9 a( G) C6 P# ]& Emongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:/ @, ~+ ?8 ?' A& x$ w
+ g7 }* f: \! `$ G, _& i; Q: O" ^' C
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions- w' A1 r9 q3 h  B' _/ _

$ n5 W# A3 B/ s' \+ O3 n7 P版本二:! D' X$ x4 J+ ]" X, Q, X
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin

$ O% l/ D2 [& Z1 ^
  1. use admin
复制代码

7 s: X5 E6 F5 |" G, J
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码

' {2 _9 K( x7 I4 z( r% f
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

+ N+ \# g. i! {; S
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码

5 P" ~+ h: Q4 Y5 `+ a- w  G
         5. #删除用户
  1.           db.removeUser('name')
复制代码
  L8 j& h" F; x- E. w4 y
         6. #查看所有用户
  1.           show users
复制代码
( w* o1 g9 Z6 t: x9 O6 l5 X
         7. #查看所有数据库
  1.           show dbs
复制代码
) W4 W4 I  o7 U$ L  J. r
         8. #查看所有的collection
  1.           show collections
复制代码
4 V5 U! P: F2 d% j4 Z2 I, Z
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

" A& _( e* w3 U
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码
, N" a6 U2 X7 ]# l4 {7 K1 k4 v
        11. #修复数据库
  1.           db.repairDatabase()
复制代码
/ w; x. C9 Q# T9 ]3 @( g# }
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
4 x8 N9 z, j/ T4 v8 P! f: d4 {
        13. #查看profiling
  1.           show profile
复制代码

- k# L/ |% i. x- q# [: t) n, J
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

" ~- P* z0 H, T! N6 G
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

, j, x, w: m7 l% Q7 v2 G5 k
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

5 ^: j; H8 ?% w5 G8 [9 ?! A
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码

# c3 Y  M5 E& K) v* h3 t
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
9 y# m2 i, ?8 o# |. t' q( s
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

- L- \1 s: t: a+ `% D7 X' c! s
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码
) c' _) o8 s+ o
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

% M1 t6 X/ `, _+ J8 u: T& p
   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()
" Y' ^( E2 w7 u$ ~* b$ B: l: B2 W
6.  高级查询
条件操作符
# x, Z9 L/ q* J7 [7 ^$ ]
  1. $gt : >
    - X9 v! o! ~$ I5 O- e( V
  2. $lt : <
    8 e9 q$ c6 A9 U# ~
  3. $gte: >= + {: L3 [9 n: C5 a
  4. $lte: <= 4 L0 O, t9 A; K; W" K# s  i
  5. $ne : !=、<>
    8 g9 p+ k8 X6 Y1 @6 ]" H
  6. $in : in 3 o  u' O6 S$ j) z9 W
  7. $nin: not in
    8 x5 e; o9 o3 @3 F; U5 @( r
  8. $all: all 0 i4 i' E" b% h7 A# r, H  u& W
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
9 f3 n5 B$ e  G
+ m7 m# S: K) N3 M( Q! h# W, l* C8 Z& e
查询 name <> "bruce" and age >= 18 的数据 6 y( y) p) e% ~# M7 X
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

6 N& S+ j$ r9 F$ O
1 H, L4 D! T% P5 v6 ]5 _# w查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 * M/ {# ~/ \5 W
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

0 j1 a) I, E- D! _9 h/ ~4 D) z0 r2 q3 \( {7 @+ I. l
查询 age in (20,22,24,26) 的数据 , L; @: ~, n4 U7 A" U5 l
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

  \! T5 _8 g  Z% s1 g$ G' K* V! Q4 O8 G, `  c$ l8 |7 m. ^
查询 age取模10等于0 的数据
. N4 X8 u* n& H7 x  c
  1. db.users.find('this.age % 10 == 0');
复制代码

7 k- C( y$ A# Z- ]或者
4 l0 I* p9 b+ u2 f4 Q
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

: D& `2 ~# ^+ P% V, D5 h& g2 l$ a! k4 q7 \' d, E1 W% t
匹配所有 * O" D. U' W' E0 I, N
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
# L( S! M3 H: i; I) R7 d) }7 B
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
  C2 h6 [! }6 }$ P可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } . m2 f% a1 U4 {8 M/ U
# p$ f7 n" _* X8 v" y
查询不匹配name=B*带头的记录   I# @. z  t/ z" Q$ E$ b7 L4 o$ w
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

* ~. c9 q! X. Q8 l6 G& s. q: @查询 age取模10不等于0 的数据
! D7 M0 m0 \6 x& c3 }6 n/ o
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
- C2 d) o; O4 F5 }( G, o

1 Y* O' k  s2 |) i; k5 c! Z8 i! `#返回部分字段 1 t( |  v/ H' ?, C. U8 m
选择返回age和_id字段(_id字段总是会被返回) ; L/ ]9 ^% W8 @8 I
  1. db.users.find({}, {age:1}); * k) V1 v2 a1 F" b( q4 b
  2. db.users.find({}, {age:3}); 0 w. {# h! N) m8 F0 \% @* c9 \
  3. db.users.find({}, {age:true});
    ( K% F' h, ~" g! [$ I% r( |
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码

! o# I8 E# Y/ P0为false, 非0为true
" V$ c1 \7 j+ E6 ^2 q8 _  D* M1 ?1 R4 a+ H7 _( T7 H
选择返回age、address和_id字段
% C; _: t3 e2 m2 g' x& Q+ ]
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

# L* _, E4 v4 C% p! P5 N1 @% V  p, g8 f
排除返回age、address和_id字段 5 g+ k% p% ?2 p6 o
  1. db.users.find({}, {age:0, address:false}); ! q5 v+ B2 A7 |7 D
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
$ G& N2 D. f3 a1 ^

( j* U/ l' I  k9 y* ~5 ^数组元素个数判断
' H+ e2 ^* ?' I7 R3 t对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
2 C& F0 v9 L# `7 R- j. G5 Y匹配db.users.find({favorite_number: {$size: 3}});
: m7 p4 @+ w; o: x不匹配db.users.find({favorite_number: {$size: 2}}); " W1 V, E8 a$ `' G. b3 P

. I" f( T6 `+ Y0 i% }$exists判断字段是否存在 . o' k& b0 J2 M! t9 p7 D, ]* c
查询所有存在name字段的记录
6 ]: j1 o: o, V& n1 @4 c5 r7 ?
  1. db.users.find({name: {$exists: true}});
复制代码
! [( y4 [6 d  `( d( N: Y8 h
查询所有不存在phone字段的记录
+ y$ e; p: y3 \& W. x* Z4 e2 S
  1. db.users.find({phone: {$exists: false}});
复制代码

& E. j7 ~. `' g. K$ g0 g& h9 W3 O5 z/ R- ]
$type判断字段类型 2 g! `% W. f3 W# K
查询所有name字段是字符类型的   P- q) o; G# p; x) O) e
  1. db.users.find({name: {$type: 2}});
    ' t+ Y5 A, ^6 w3 D/ [
复制代码

" `: ^3 M; o$ k5 s1 v查询所有age字段是整型的 3 k  P8 _) L4 o# V
  1. db.users.find({age: {$type: 16}});
    ( _% H% J! O5 U2 q
复制代码
8 ?+ u5 u  {2 v' G, t
对于字符字段,可以使用正则表达式 6 O$ H* X, K4 E
查询以字母b或者B带头的所有记录 / k+ r" I! y/ }2 Q
  1. db.users.find({name: /^b.*/i});
    7 t' B! \, o( x4 h; j1 k
复制代码

9 }: B9 }& U! e2 {: G8 t3 [$elemMatch(1.3.1及以上版本) / l% J% y1 @1 d! d
为数组的字段中匹配其中某个元素 4 ?/ B7 z9 y7 q4 `6 ?

& g2 v$ |) }6 N+ qJavascript查询和$where查询
6 p4 A* O6 u/ e/ x查询 age > 18 的记录,以下查询都一样 2 k0 @+ Q& e1 M/ m2 N. k
  1. db.users.find({age: {$gt: 18}});
    ! v$ h/ w6 w0 C+ N' O5 Y
  2. db.users.find({$where: "this.age > 18"}); $ W  H- F. ^4 ]* Q
  3. db.users.find("this.age > 18");
      b; P) O+ X$ S* h
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码
$ x3 @: _) d" w

3 M5 I: B9 w6 e9 C排序sort()
  |( X6 X# C2 e+ f+ H0 q) c; {以年龄升序asc 5 T9 g+ k% i: b/ `
  1. db.users.find().sort({age: 1}); * ?& Q2 N$ u. G: ^7 u. q; {& M) n
复制代码
3 W* J. x' G8 i1 d
以年龄降序desc
2 z" i+ W9 |* B7 Q5 c0 ^; V
  1. db.users.find().sort({age: -1}); * ~! }7 X# o- r; B- M
复制代码
* R! K' N7 w5 R( K$ M
限制返回记录数量limit() % t) C9 Z* z! }) b5 ?0 @3 {
返回5条记录
% v4 x4 o, X+ f' I
  1. db.users.find().limit(5);
    & C' A; G) E7 d' w6 D, v
复制代码
% [5 o% l0 H; U% \, y7 @1 T" x
返回3条记录并打印信息 8 d2 o5 O- k$ f8 g9 O, _
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    9 @1 S7 A: M( h+ f& c
复制代码
  ]; N. |% l1 i7 `
结果
& w" i& v4 z9 j2 \3 H( ^# T# a
  1. my age is 18
      c% s/ D$ f" _" H% j8 Q$ B
  2. my age is 19 ! F' R  e4 H( V- @
  3. my age is 20
复制代码
4 V, G, ]6 e& ~8 A' w0 r
$ K( a7 ?# B( `
限制返回记录的开始点skip()
1 }5 T  B/ P/ _" @0 O+ I) @从第3条记录开始,返回5条记录(limit 3, 5)
  o& ], u5 O6 y
  1. db.users.find().skip(3).limit(5);
      C6 I: ]( \0 ~5 E8 B3 ?% i) C
复制代码
  K+ n/ G- r6 K2 W
查询记录条数count() - ~9 O8 D  k/ H8 E5 L
db.users.find().count(); ! d  z/ m2 t/ p- j
db.users.find({age:18}).count(); ! H' `6 w  M& E% l- N- E& {
以下返回的不是5,而是user表中所有的记录数量 0 o0 Q0 Y  H( e& N- u
db.users.find().skip(10).limit(5).count(); # j) T" r$ P& P
如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 4 L" `+ K' F% b2 U: Z/ v
  1. db.users.find().skip(10).limit(5).count(true);
复制代码

* M7 G* I5 a" `. O% B. R. P0 S/ C5 s% M
分组group()
6 q+ e4 P1 K/ T假设test表只有以下一条数据
. b9 [, c! P! S+ y! L
  1. { domain: "www.mongodb.org" 3 Y  I! z0 K6 h1 ^7 a4 {
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} 9 N1 m5 {+ h* k. I2 D
  3. , response_time: 0.05 6 x. H' p5 p: K: c, B) N
  4. , http_action: "GET /display/DOCS/Aggregation"
    & h6 b1 L; Q7 c! q' ]! P4 u
  5. }
复制代码
" C) B0 k2 U9 z7 J3 v1 M
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
3 d  y6 c+ {- `. o
  1. db.test.group(
    / @# V4 c, p7 p9 W
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    % C1 N3 e% s1 i5 w
  3. , key: {http_action: true} + `! q9 K/ ?7 O2 n# }; e7 F% \
  4. , initial: {count: 0, total_time:0}
    ! y7 B# E8 S) m) j: N. C. m
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } " U/ J0 q- R+ |2 a$ ]( p
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } 2 j! k  [- O4 c- X- t/ F/ q* c8 S
  7. } );
    2 A" l1 \6 P' U1 n& c! A1 W

  8. 5 ]% S& {% M/ B( e4 W. `
  9. [
      h0 F! u# j. G4 _  W
  10. {
    # L' C. j3 m% d  d* w/ k/ C% m- C& Z
  11. "http_action" : "GET /display/DOCS/Aggregation",   ~3 t1 r/ G) f6 N( K3 \
  12. "count" : 1,
    ! b5 a( g! @! O! U, v' U
  13. "total_time" : 0.05, 0 }! J9 b4 V" |/ v* X( R
  14. "avg_time" : 0.05
    % ^  C  x8 C0 O
  15. } 0 f) n  ]5 ?$ _% ^
  16. ]
复制代码
" I* G" r8 l! F+ I7 x3 z

) s6 |+ |5 O. {- d+ N5 ^# ^+ G
7 d. l; H' \6 C; x& \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( H$ g! n" O# ~- g, J
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

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

4 s+ m" b  h4 |
0 V0 U- q& b% b; l9 i
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
" W$ V& o9 R% s6 V

! y1 U4 q: V2 _
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

% l$ }" I) M9 I/ l) ], L1 y+ Z+ d  {. q9 P5 H" V6 `  a
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
% k5 p! x/ Q' J' G( m. Y
/ s7 w1 D& y" ]7 J
输出如:
  1.         
    7 y6 h3 g4 F* p7 x/ @6 ?
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

( Z' a2 H' O6 o6 K/ `
% w4 Z* V1 O9 `) z9 ~4 _' F5 n8 x
" d1 R  j- }; y* H$ e2 ~3 `4 a
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"8 m4 N9 H; O' q# p; x  o! y' H
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    % S# a: `; z1 d6 \- [+ Q, m
  3.        xmlns:context="http://www.springframework.org/schema/context"
    $ R9 \' |% B- E+ X* F- M
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"2 K. l5 u" Z7 Y
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans8 X! q$ i* O0 N
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    4 P7 Y  J0 V  b4 V
  7.           http://www.springframework.org/schema/context- S7 ~" q* d/ ?( h
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd% a" F2 y! o, m3 F% J
  9.           http://www.springframework.org/schema/data/mongo) R' f7 }) o+ J
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    * d  q7 S7 A. W: x$ L1 X' O2 {

  11. ( z2 I) m* }- }' t
  12.     <context:property-placeholder location="classpath:mongo.properties" />- D/ R8 l5 V! M% T
  13. 3 H4 Q" J5 B' W6 b, |: ]/ p6 D
  14.     <!-- Default bean name is 'mongo' -->
    * \* r7 o* U. G. i
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    3 V* z& b. ~5 e  t4 u8 i
  16. % J% D' F9 M* [9 l- p
  17.     <mongo:db-factory id="mongoDbFactory"5 j6 }( J  n4 M/ K
  18.                   mongo-ref="mongo"
    # B+ y& r' u$ w2 n, t6 X6 a3 s
  19.                   dbname="mongotest" />
    : U' i  o5 b6 {5 F5 G

  20. 7 G* s6 V! [* L
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    ' m  z3 G6 w2 g" R' [* W
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
    ( ?+ j7 n9 L0 f/ }$ U6 L1 e5 h/ u7 v
  23.     </bean>
    : `) I! j* f/ L; W0 Y5 O
  24. </beans>
复制代码

4 A% a  W0 ~$ k, ^; r- d" h
6 C+ ]' {$ q# F" ?$ \  n
maxmin的测试
  1. @Test. z8 z! x# z- O" G8 x
  2.     public void testMaxAndMinAge() throws Exception {* }, ~  ~1 k) ?7 q- y+ o! l& w+ q
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    2 ^! V( f" h3 v( m2 A& J( S
  4.         Person result = mongoTemplate.findOne(q, Person.class);- ~- F2 ~  k/ j! L% F: h- Z& @, a
  5.         log.info(result);
    & K5 d$ k8 I8 e9 X
  6. + _1 f8 Y; X% k0 ~# m
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
    ' a! D1 [; r/ |) i, w9 `9 M; |
  8.         result = mongoTemplate.findOne(q, Person.class);  |# x& O7 c" s8 f
  9.         log.info(result);
    / W( ^  `% V& v) b- F
  10.     }
复制代码

9 p* {/ W, N- {# h
, H( A7 G6 D2 M1 Q- x& Q( ]3 N4 F
distinct的测试:
  1. @Test# I- p2 X& f) s, [; J* U
  2.     public void testDistinct() throws Exception {
    # H' ]8 a7 J! I& S: i
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    . d; @$ c3 Q8 L! a& Z1 d
  4.         for (Object o : result) {
    8 H, n+ c3 G) ?8 U1 Z* i
  5.             log.info(o);3 y. T& a/ u* `+ I
  6.         }7 H2 C8 Q  e. c( `6 Z/ l0 {
  7. ; B' Z1 _3 A+ W. o4 L: o
  8.         log.info("==================================================================");
    : G8 P1 [7 v- X/ ?; v# U+ X
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));! s! A, r# @2 t: g! t' p& t. i
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    ! @, q) o! \3 ?/ l# ?
  11.         for (Object o : result) {, C6 H# `3 y$ @9 L8 n, n
  12.             log.info(o);% {% ^$ `' a8 V, |' F0 ~+ ]% x5 z
  13.         }
    6 ]# G) l4 Y8 a. L; c3 u; ]+ g

  14. , |9 R0 \2 n* U) Z, @3 W. O3 g
  15.         log.info("==================================================================");
    . g; g5 v' y/ }* D0 x4 K# o: [4 \
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");$ r4 Y+ G) J0 B: U% [$ d
  17.         for (Object o : result) {
    ; ~' W. a8 R& w. r* C- R6 `2 ?
  18.             log.info(o);) Y' v3 ~7 C3 X1 x* V
  19.         }. k+ @: C8 I4 k5 ^2 ?
  20.     }
复制代码

* P, ?, e" _# O! b: g( |! m0 r3 f
9 b* \/ @; ~7 F
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567) y) v$ L% `0 d, E& c. H% j5 L
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
    ; j& F& {1 U3 r6 y& N
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789+ v1 y- w, _' O1 y. W5 F' r
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
    & j3 m0 p9 ~, s7 I) b; }4 b# N
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni& ?% Y9 K$ g4 J
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
    ( n. `+ D* P7 L, e) K4 M/ [2 _
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456. M8 b# Z9 m8 \
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================" E1 w! [* x9 O0 N
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    , S' u8 A  o. I! a! J) I& {7 q
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    " Z2 v4 B( m) T! g6 M
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789; w4 H4 E7 W6 P
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876544 w3 X+ _; `; g5 w8 ]' _. W
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================& C! N: P. }3 {8 ]: r9 r# D1 L
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
    8 V3 l+ j2 {( @, H5 U+ i" T! l# B
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb6 @- P  `  v, s3 E
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc; l  v( d( o  i* V# q' s
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
    * l0 J5 L9 `6 J0 ]- F9 F$ X' K
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx, Y2 P1 e2 B$ L6 @$ F8 L; Y
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    & G; J6 R2 K4 z) g9 v. |
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    3 c- L. R' f5 U
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr( ?% |" L' Q6 w% l+ o
  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
复制代码

* K! W' r0 o0 P; Z, r. U% x9 W. W0 B# w& 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等信息。
4 r1 V6 M7 ]$ W8 _% [

+ [* b- D, u$ F2 f' y' [3 x! g( j. u5 K# q* I: F) P$ ?7 I5 ?
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 支持支持 反对反对
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

GMT+8, 2026-1-30 11:36 , Processed in 0.068985 second(s), 22 queries .

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