cncml手绘网

标题: MongoDB高级查询用法大全 [打印本页]

作者: admin    时间: 2019-7-4 17:21
标题: MongoDB高级查询用法大全
版本一:
* S! v- c" Y+ i1 h$ b% o! G$ E9 s9 Z  ~; e
1 ) . 大于,小于,大于或等于,小于或等于% t* ?9 D, I) [1 V
9 O( z2 U% T9 y$ c) |5 T" J) d
$gt:大于
2 z. G& R# Y* G" j) Y$ d6 q/ m$lt:小于. ~- `( ^3 F9 U5 x. ~$ e" v. o; U
$gte:大于或等于/ J( x9 Z7 l  }$ |7 |
$lte:小于或等于+ _+ R' q( [8 ?" A2 r! w" s

( Q. o: P7 D# B, k9 _1 E# c例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value
    ( ]9 }2 l$ U0 q5 K9 A
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value
    + r# \2 X1 m) W, G/ I# m
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    / Z8 G2 T) M0 s' `
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

* I8 h  z) c  m9 ^  b8 Z
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    ( J3 V! O7 B* s: T8 d$ D% s9 N
  2. db.things.find({j : {$gte: 4}});
复制代码
- g3 X9 ?& `/ z3 E, K  K( }
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

7 }. `: R  `8 Q8 B# P2 S
. E8 d) D# h6 l* V/ a; Z" O( @) u( Q9 F0 W% O$ w; _: d7 E- `. _
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
9 C: i- G' `& n
3) in 和 not in ($in $nin)
" t6 g; }0 y% M# `; c- b* D2 k6 Y7 [
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码
1 l1 f1 \8 M$ s
例子:
  1. db.things.find({j:{$in: [2,4,6]}});/ D7 O! R5 B$ Z6 D& g. ]
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码
* b4 Z9 ^, D- Q4 `, S: x
! C, A9 }5 h7 ?9 V# l% }
4) 取模运算$mod: I: U' }: d. t1 h; ~- L
) S6 R' M( a" b
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码

5 {5 b( |* J6 M: B) G
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码

7 E) G! w2 d$ ~2 e$ r9 C. ]

9 C, j# t) i- B( U* r5)  $all
8 W3 R+ z' }7 K7 U5 g/ a& D: L  `7 V- W  y1 t  w3 ^+ t
$all和$in类似,但是他需要匹配条件内所有的值:
9 q' P2 q& \! g8 m; Y
3 i& Q% ~" F9 d! U如有一个对象:
0 n" i4 Q$ d7 k
  1. { a: [ 1, 2, 3 ] }
复制代码
  m4 e. J8 J, K0 b
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
7 g* I6 \% r3 U' X* v& p
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

4 u5 L8 y& u6 \4 q

: i% m- F) F; B  ^6)  $size
) \$ j+ P* f& v6 X
3 Y2 B, V" Y/ g. p$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
/ S' r& ?0 b7 h7 F8 v7 l
% e4 t' |9 G( h% J下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

# T" ?1 R$ \+ ?
官网上说不能用来匹配一个范围内的元素,如果想找$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.

" o) ]7 Z+ L- H) y
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回* W$ H! p' l3 r9 M6 y5 G
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
/ M) {! l7 B8 c7 k% J0 s3 Y
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string
    ) b1 W7 w- b3 g- N
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
* N6 |' x: u9 x; S  I5 Y* x
9)正则表达式
- v. o3 h2 |: g$ s7 [
* l  [. S- d4 n1 P$ [0 M/ `4 _4 Gmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

! h, J( ~2 Z' W) \) x) T; d
10)  查询数据内的值
# t$ L  Z9 W' h: m* T! v  d: {4 h5 o; F4 \- j+ ^  @- n
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码
! x4 N# \# V9 B& i# o/ ~3 P4 c0 }
11) $elemMatch
* b0 ^3 S) X# D& m, y2 A! |# @$ Q, Z! K
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) % y$ A/ f; ^( D
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    6 Q; I& T( e# E! G
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    & r) g- \% Z  U$ Q
  4. }
复制代码
% e2 }$ m4 Z* H# X7 i3 }
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )+ ~  U* ]9 x5 B# O: C2 n  q4 c: e
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
8 H" `6 {3 w7 h) G9 ?- P+ E1 s7 T6 x( U9 W6 ]: v3 m  r
12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
& U/ R5 @, ]+ O5 ?  k- _5 }" q
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

. X: y5 {0 x, i$ L0 \- s
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
' b0 k# M# e  w9 L9 i8 |
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码

6 c# U3 d: k2 U3 {' L8 o: Q
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
; |2 N* I5 X/ X9 S9 L* j
是不能匹配的,因为mongodb对于子对象,他是精确匹配。

6 l# Y# ^8 b0 P" d5 {# G0 \! T( D
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );
    3 H) F9 j6 F4 I6 B, R+ c$ O
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
3 f( T: T7 O( S7 ^: a
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
: O8 c$ P' k2 z* l! g) [5 N! r; a8 M
mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:9 G2 O- L8 b/ J3 f2 B2 J( E4 \
, E: s1 S( S) I7 w( S
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions. T7 I# O- u# v; z7 \

; Q. M. C4 w+ F版本二:/ I  ^! R$ s4 g3 a; f  r
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
- b4 p. I: P; K  u3 E1 m0 x! N% C9 w: B
  1. use admin
复制代码
- G- C% A- I# s
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
! P( x4 |, J& J8 S; Z; G0 K$ D9 Z
         3. #查看用户列表
  1.           db.system.users.find()
复制代码
; ]$ n8 [/ r5 q
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
! }8 [7 E; J6 C! [3 g
         5. #删除用户
  1.           db.removeUser('name')
复制代码
& J- k' ~9 }6 m: ?0 e* `7 x) k
         6. #查看所有用户
  1.           show users
复制代码

7 h' ~: W7 B) S5 p. V7 q- P
         7. #查看所有数据库
  1.           show dbs
复制代码

0 u" |: Y* d0 w  c2 a3 `8 K
         8. #查看所有的collection
  1.           show collections
复制代码

2 I% G$ W$ i' w+ g1 j3 u
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

  X8 c5 U$ w% Y* U4 p" B
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

  V9 W; }6 j3 L
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

5 D2 p. N" m0 `; M' j% d
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码

% Q0 I6 V6 r7 l# O! f2 }) B
        13. #查看profiling
  1.           show profile
复制代码

  h- S9 y/ ~* i. b: g
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
$ j1 r. K5 m/ S& v) L
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码

  `" u3 [* B) S. x  e- w
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码

# X: I( w$ C' A6 q& l7 h0 x
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
1 z9 B2 N  w( I3 W) w
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码

7 _5 N; I( P$ o1 P/ ^
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
" V$ R7 u; z: j/ o
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码
/ g4 g' m9 Q. u, v% K$ l7 b
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

. b. L; Q4 M9 w- `2 a: f! o
   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()
  c6 P$ U+ O9 d% j+ m7 k: o
6.  高级查询
条件操作符 ( u% }+ P5 E. B% [0 p
  1. $gt : > " r/ f: U) o/ W
  2. $lt : <
    ( x, q/ M" Z( ]
  3. $gte: >=
    . V# m- x( o0 C. _
  4. $lte: <= ) P3 R# |6 M7 r2 c# _, ~. }
  5. $ne : !=、<> 8 f+ Y+ _! j  b' n3 w$ s
  6. $in : in 7 i# T5 Z! g  s; x
  7. $nin: not in
    ; h: V. ]  ~3 o
  8. $all: all
    ; a# w, K: i$ |% Q$ x
  9. $not: 反匹配(1.3.3及以上版本)
复制代码

1 ?) D6 B: e2 _1 H" |3 D' ?* O2 I, w3 {' E9 e
查询 name <> "bruce" and age >= 18 的数据 . S. d2 |1 x5 ~
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
( n" T) }7 q8 U" L  x

' E7 D8 o6 f/ H1 Y) Y查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
, z& h8 C& w5 H  p& m9 s) A& W
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
& [4 o+ z' k# Q1 v; w1 [2 r
/ @1 ], s7 u7 M6 c
查询 age in (20,22,24,26) 的数据
+ Y, F7 C$ o! w0 E- {9 k
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

- y3 L; t8 u  h$ ~* ^3 h9 s8 T
7 ~5 h/ J6 O0 u, W% ], k查询 age取模10等于0 的数据
: V+ O3 _% z: z$ t
  1. db.users.find('this.age % 10 == 0');
复制代码
  l- h' x/ u0 R# b
或者
5 f+ ]( q+ \2 r% k9 Q3 \( @
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

+ u  q, g7 k/ Y" N# U, ~7 \8 b4 @# H5 K% L, l" g
匹配所有
7 _: ^( s# `3 M9 F9 L6 W" X1 {2 ]
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码

0 f' g( P. h, l6 H2 B) C9 e4 J可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } , M8 M8 p; Q% w# a  ]2 B2 L
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
2 _) o& ^' }  W0 Q; S8 W, k+ l' w
查询不匹配name=B*带头的记录
1 j) ~5 D. ^  D. \8 c& g# H
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

) J9 v+ o4 o# m" r/ F; z" q查询 age取模10不等于0 的数据
* B( }& {# i( O5 c6 t5 T$ v
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
0 k) B) t1 q! V) O

6 {7 e& k( Y$ n: u$ M#返回部分字段
7 O9 ?1 L5 m. T' e1 D/ y选择返回age和_id字段(_id字段总是会被返回) 5 ?! k2 k& i# g
  1. db.users.find({}, {age:1}); $ @5 D4 A. S1 O
  2. db.users.find({}, {age:3}); 6 p8 u! l6 a- J; t! ]' x
  3. db.users.find({}, {age:true});
    & w4 Z# w8 U" }7 C
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
" J0 }7 h6 G5 m/ b; K1 e
0为false, 非0为true
7 G$ E3 N% n) E' D# @/ i9 N/ B# |- v  M: N6 J# d  a7 @% C: ^
选择返回age、address和_id字段 8 ^/ D' T- H6 w+ ~
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
5 b' f  t# V0 L# R& r, ~$ f: n

( e# Z, ]1 K" c3 a6 T: i3 l排除返回age、address和_id字段 6 G6 e% s. d6 P1 W0 O, o
  1. db.users.find({}, {age:0, address:false}); , Y4 C* T; j2 I" X. U8 {
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码

  K1 Y. ^" S: q' w3 v
& b2 i  |' M$ K' d, P0 f数组元素个数判断
! _% m1 }  I2 `- |对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 * O& g. N# ~8 L$ l7 y
匹配db.users.find({favorite_number: {$size: 3}});
' p2 |0 H7 D  }$ ~# E  u不匹配db.users.find({favorite_number: {$size: 2}});
+ \1 _+ j7 h$ q5 Z6 ~
6 c  W  ^' n. T( O9 D; S$exists判断字段是否存在 9 k6 J& i3 X2 G
查询所有存在name字段的记录 % p5 [& e  O1 x  ]
  1. db.users.find({name: {$exists: true}});
复制代码
# T8 d7 w. h) G* e; n+ t
查询所有不存在phone字段的记录
( a( [% @! k  j, d8 S- [
  1. db.users.find({phone: {$exists: false}});
复制代码

: ^# n+ }( i- C6 Z% s0 H
; {0 |% ]2 E+ h$ ?, I  N. Y$type判断字段类型 2 I1 }$ c$ p0 C' F
查询所有name字段是字符类型的
# N: x  u  Q# l' q9 B8 |! K3 _
  1. db.users.find({name: {$type: 2}}); 1 ~" ]8 P* A( ?* c
复制代码

5 L6 Y7 I( ~: o" A0 c查询所有age字段是整型的
, k# e2 q0 X8 e" Y. L
  1. db.users.find({age: {$type: 16}});
    ) N% ?6 r( }. B8 J  v) f
复制代码
1 R6 D( `; j: K8 s% q/ O
对于字符字段,可以使用正则表达式 6 N$ P  v  O) g+ [! n. {
查询以字母b或者B带头的所有记录 7 P3 C5 L. X: _% M
  1. db.users.find({name: /^b.*/i});
    0 b  l; v. V4 _. f, w6 V% `
复制代码
. F3 a) Q' j5 H) ~
$elemMatch(1.3.1及以上版本) - `- U* G+ i$ S$ N& E0 [
为数组的字段中匹配其中某个元素
! o& z! m3 K% g) Y2 Z, i$ I% Z9 C
( k8 z0 Q$ |: UJavascript查询和$where查询
) g. }7 K2 K! _/ d' b0 W+ d查询 age > 18 的记录,以下查询都一样
, j. }) y: v4 o
  1. db.users.find({age: {$gt: 18}}); ! L, e4 Z+ G( ^* x
  2. db.users.find({$where: "this.age > 18"}); * P4 q  V, Q" v/ V7 _. I* y
  3. db.users.find("this.age > 18");
    / i6 |' R) Z+ y- p. C1 N5 j" G. A
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

3 v3 H6 p$ c+ g% _5 U
8 \, N* f5 n$ y) f! u, P排序sort()
- ]5 t& [$ k% @以年龄升序asc
6 _4 f# |+ o- r+ Z- ?
  1. db.users.find().sort({age: 1});
    / r/ w/ d: V1 K* J
复制代码

4 R( x& A. \. E3 H以年龄降序desc 1 k% |5 I+ m! v3 U& V
  1. db.users.find().sort({age: -1}); 5 Y& |* k/ T7 I) i6 q
复制代码
: D. O. W/ l) D, s; {
限制返回记录数量limit()
3 Q% c* K' ^0 i' d返回5条记录 " s* O6 p6 l+ \, M
  1. db.users.find().limit(5);
    ' ]( R, n+ K$ V( p
复制代码

7 m0 p5 g; H5 U- r8 o" N返回3条记录并打印信息 # ~: f- u( F* K+ s% j9 z' z' O
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});   {; ~1 v$ z! C& _$ i8 F$ t
复制代码
% m5 W1 P! p  M' v# |
结果 9 D6 W" O& E# B: r
  1. my age is 18
    + v: x9 J* }$ {9 ~8 p
  2. my age is 19
    3 \- p8 h2 f- c3 f! o% L8 \8 \4 p% I# {
  3. my age is 20
复制代码
; ~9 \! m6 g5 \5 C, K) l

: W2 C3 d  G" d$ E6 L, Z限制返回记录的开始点skip()
5 @9 o- p1 w! X9 d从第3条记录开始,返回5条记录(limit 3, 5)
) i. b0 Y$ X( F* ~: w
  1. db.users.find().skip(3).limit(5); ! Y3 Y6 [  _/ V8 _7 I
复制代码
& X1 Q6 y1 e" E  F5 p
查询记录条数count() - u( p- R& D+ E' V0 X
db.users.find().count(); . w" q5 a) Q" l# h
db.users.find({age:18}).count(); * F9 g- Z0 W/ T3 p, ?
以下返回的不是5,而是user表中所有的记录数量
$ e' k2 b- {; v) O) odb.users.find().skip(10).limit(5).count();
# z+ {* ~- w9 X4 Q2 W如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
7 h; P! z4 ~" U" \% a: b. N$ m/ s
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
' C( i+ r, A  U9 b6 A3 G( d
- h5 Z! _: l! g9 f7 \+ Z
分组group() ' n) }& G& @& ?% t% o4 e: M% O  a
假设test表只有以下一条数据 0 L1 _- G9 S# e( O# f! j
  1. { domain: "www.mongodb.org" # R( S7 j, q! F& ]
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} 4 b. \0 t) W1 w0 t
  3. , response_time: 0.05 4 B  j. [; v8 m/ f" Z! U- [
  4. , http_action: "GET /display/DOCS/Aggregation"
    - A5 j( L: |4 X
  5. }
复制代码
7 G$ z. y- E- Q6 t
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; * |5 B6 n* ^" A0 K
  1. db.test.group(
    " F: P. E2 Z% n1 R" m9 u
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
    9 G) [" ]* y. f  \
  3. , key: {http_action: true} ) y# M. q5 Q9 e- A
  4. , initial: {count: 0, total_time:0}
    ' v( C* K$ U: G% V  A$ o% @
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    ' _$ C" h) H* {3 k, M. w& K2 E
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count } # E& r; ]2 C) u+ U, Y, d$ B. |
  7. } ); : [# c! K% W; ~5 g. v4 ^1 C
  8. # g0 i: g) s5 e/ j$ `
  9. [ 1 D- D* L& r4 V" Y9 V( ^7 H* G
  10. { ( g+ _% p1 t1 r
  11. "http_action" : "GET /display/DOCS/Aggregation", 3 G6 R/ R8 s7 T! o/ ]: J
  12. "count" : 1, 8 O* i- `: L! ]) D" o
  13. "total_time" : 0.05, * K! i) n# [! Z* b
  14. "avg_time" : 0.05
    4 Z! p, P8 n; r- u7 N# I) X
  15. }
    . D6 J; E; ]! `6 q5 M* S- _
  16. ]
复制代码
4 ~# q1 z: P' c2 x

8 h4 t/ b$ S7 S: V
% k$ F: I: W( x# b; U* H# v/ |  DMongoDB 高级聚合查询
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。
见:http://static.springsource.org/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoTemplate.html
不说废话了,我们直接来MongoDB吧。
  • Max 和Min  n! L" Y, ~& c" r. S  c
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码

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

5 p, a4 D' t- u" W7 H4 `' `  ^4 m5 f: D  Y
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
) q0 `9 e  U% x% A# ^- k# B5 u2 @% o
* h, q# m- D! p9 `3 Q
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码

* q1 f6 Z6 y! W- E* s3 t+ \: f& y/ f5 C2 S4 B
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

+ ]& |/ F7 {9 X( p4 @4 ^, y) p& x  X8 e+ K0 K: c
输出如:
  1.         
    ) R, A6 i/ _, [% t: ~1 G
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
4 g5 P  D" M3 s4 B

0 ^% A$ @! q5 w) ?4 w
3 A1 m: \6 K: l
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"2 O4 F4 R* l. v# U5 \$ s9 y& E
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    2 Y) y: _4 q. A5 z3 i
  3.        xmlns:context="http://www.springframework.org/schema/context"
    , `0 f, Z* h4 q- C: Z) K6 ?
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    : _; l3 V# l; Q/ v' O: K# D$ {4 K" ^
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans. X/ V4 q, R2 T6 V2 _4 |; ?$ Q
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    3 ~9 i' D# C4 [' @9 a
  7.           http://www.springframework.org/schema/context5 w8 X7 |5 u6 b+ ]7 n+ c
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd7 s3 f7 J: O; [/ i- U8 u9 G
  9.           http://www.springframework.org/schema/data/mongo
    : x4 G: G) B' k* I9 x
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    % H: N- z; `' Q4 x" `1 j+ |
  11.   k! u9 W! k4 T2 s" N
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    # q9 G* S$ x$ r$ U2 _1 Q! C& g
  13. " P: t# [# M. [' X* A3 S3 j5 n
  14.     <!-- Default bean name is 'mongo' -->9 O! V' m2 C( d, h, n, O' K
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    : ^' D/ D& s' k7 M7 i

  16. % t5 R8 H, d- L% S6 E. w
  17.     <mongo:db-factory id="mongoDbFactory"
      F. ^  A* m. t! a) r
  18.                   mongo-ref="mongo"
    ! S1 X& p, D7 o8 Z9 _- p
  19.                   dbname="mongotest" />, ], {0 T; X( C; ]

  20. 1 M" k* O5 }) @" j) i$ b
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">( A$ r" ?: k7 ~" t, Q' v
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>' u& T9 k' Q& V( P! X2 M, j1 t
  23.     </bean>) w3 u( c4 ~( l& f& ^4 H6 X
  24. </beans>
复制代码
5 F# s; V1 {1 S4 T
1 B% K8 I, P4 X: y7 _  W5 g; U7 Q
maxmin的测试
  1. @Test( |# L8 Y+ @! L7 }9 c
  2.     public void testMaxAndMinAge() throws Exception {
    $ N5 q' t; d3 s
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);; o  T5 n0 e6 P. [& P5 c
  4.         Person result = mongoTemplate.findOne(q, Person.class);/ f! U1 `# E% B7 l# s
  5.         log.info(result);$ w7 @: J# w  b0 z
  6. * q4 _+ z7 \8 j
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);" }) _" N3 n6 x5 x) E8 h% `
  8.         result = mongoTemplate.findOne(q, Person.class);: j  L' J: g! U8 E# G; Q
  9.         log.info(result);+ k, d; V$ k0 B) e3 h
  10.     }
复制代码
+ {% e" B( U0 f8 h. P
, A9 S! I5 h1 W5 n$ E- B3 |# O! f
distinct的测试:
  1. @Test
    4 r' Z8 \4 J9 @3 {5 l
  2.     public void testDistinct() throws Exception {
    9 t/ w8 k. B, Y" \5 S. z) `
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    ) s3 F/ K+ T4 Q8 [# S
  4.         for (Object o : result) {0 ]8 E) B0 F1 T4 A" q% d
  5.             log.info(o);, Z, E5 Z; @, @6 c8 c
  6.         }
    $ r- R2 \! Z/ E! z
  7. + {7 ]1 d8 G% X% X9 |- ?  K! f
  8.         log.info("==================================================================");# ?2 A3 q' o9 Q# Y! q# {! |
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));
    : ?  S3 {- l& k4 \
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());" b) c- a& E( r# e  Q1 b" Y0 z
  11.         for (Object o : result) {
    & u1 |  v  |$ z" g' H/ l- W
  12.             log.info(o);
    * Z/ g9 N, c! ^
  13.         }: |7 L! g! z8 D" ]% Z/ D: t

  14. 4 E  B; g6 X" H
  15.         log.info("==================================================================");
    6 t7 E, w* m6 v- ?/ t, f# x4 _6 }+ m
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");: ^, l, E0 f0 o( E3 n8 }. O" Y1 F
  17.         for (Object o : result) {9 |* V# {- Z: g+ w
  18.             log.info(o);
    # A: b& f& A- ~  x" h) z7 D
  19.         }7 G! a4 V8 N: Z( k
  20.     }
复制代码
2 }6 x' Q2 Z; E0 f7 w* d
$ u4 B  R) |' V  B. y* B
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567  b) k: K! [4 Q7 s* s- s
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 3456783 t; ~# O! |  k! N6 K
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 4567891 s+ G/ |5 Q+ d% [
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
    , w  V4 j8 ~2 O7 M
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    3 W4 E% b6 d8 }
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo" h  M+ ~7 X# f; _3 h0 N
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    % F- v% D. A6 v$ ?; F$ g' X
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
    4 F7 a# q* ~0 i5 u" s
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567; E8 w" U* X& N# T' X2 H
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678) l" e' m3 R* I0 q8 N: B
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789& }8 D3 L" C7 d* d7 l, F9 S
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876540 {, j9 u8 z. \2 {$ r
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
    : K3 X+ x' A: V4 S$ I
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa+ q4 Z4 A/ Z! B$ B: e' a
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    5 }# Y' c+ Z$ F
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    # a' @5 y/ H4 ^2 X
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www7 |& G9 P% p, |0 c) m* X
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
    ) c$ Q" k& ~" ^. I/ r+ }( X
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy7 D4 P6 j* X, k5 c) w6 }2 |
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    0 N9 p3 r/ u9 X, Q
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
    9 T# V! K" ]% P/ A
  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
复制代码

, u& Z$ ?4 r3 Z/ L5 _% m$ f8 [
3 p+ m$ |7 ?+ f" ~8 W
这里我要特别说明一下, 当使用了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等信息。
0 [1 w# R5 e# K
; v2 R* k' X. K; W7 y3 \; D9 V
4 o/ I+ W) G  \; Z5 ?1 d, T





欢迎光临 cncml手绘网 (http://www.cncml.com/) Powered by Discuz! X3.2