cncml手绘网

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

作者: admin    时间: 2019-7-4 17:21
标题: MongoDB高级查询用法大全
版本一:
1 ^! q) `  Y1 f3 S
" j# r7 ?  {- X; h, C1 ) . 大于,小于,大于或等于,小于或等于
; W4 O7 q% h. a; M. x! l) b
! g( o4 N0 _8 C9 [0 o9 p$gt:大于
/ H. K' T; f4 y) ?$lt:小于
+ T: O: V6 l! o$gte:大于或等于1 l$ ~/ D- L6 N+ |
$lte:小于或等于
% }0 M+ _/ B6 I; f5 K" L
  F& r' b* {9 [  n& p2 L例子:
  1. db.collection.find({ "field" : { $gt: value } } );   // greater than  : field > value! g$ z: {4 U! q# x- q: m- c
  2. db.collection.find({ "field" : { $lt: value } } );   // less than  :  field < value' i1 J6 F; R0 n8 L
  3. db.collection.find({ "field" : { $gte: value } } );  // greater than or equal to : field >= value
    ) G7 n- Y9 h( ~6 C  A
  4. db.collection.find({ "field" : { $lte: value } } );  // less than or equal to : field <= value
复制代码

" N6 X% z" O3 C% K. S  i
如查询j大于3,小于4:
  1. db.things.find({j : {$lt: 3}});
    5 d. ^" E9 q) V$ }2 L
  2. db.things.find({j : {$gte: 4}});
复制代码
5 G  R- D# ]! X: b9 |, P4 s  G. L
也可以合并在一条语句内:
  1. db.collection.find({ "field" : { $gt: value1, $lt: value2 } } );    // value1 < field < value
复制代码

! I% h) h7 Z( e$ b! f1 S, Z% ?2 i9 f' Z% ]
, s+ |$ _9 V/ D5 Q
2) 不等于 $ne
例子:
  1. db.things.find( { x : { $ne : 3 } } );
复制代码
9 e6 G4 _! ~& {; r+ a: g7 E
3) in 和 not in ($in $nin)8 G9 F/ l5 B% w; O
0 X/ A: R7 U) L4 H; U: P4 Q
语法:
  1. db.collection.find( { "field" : { $in : array } } );
复制代码

' @! |# {  }! P3 s. I2 }
例子:
  1. db.things.find({j:{$in: [2,4,6]}});* ?" [4 F+ @& L' _; G1 r) r
  2. db.things.find({j:{$nin: [2,4,6]}});
复制代码

; G' N9 \: h2 b$ a. `5 ~/ i
+ T# p2 u+ |  Q; i/ W% y* e$ Q6 o
4) 取模运算$mod$ k! E! w, i! b* s
& P5 g) m3 Q7 U1 W8 q3 X
如下面的运算:
  1. db.things.find( "this.a % 10 == 1")
复制代码
3 Y2 E1 Q" @7 N' J' }. l' x
可用$mod代替:
  1. db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
8 T/ X& e. R+ ?! C$ l) ?. k& R8 o  p, t
! e7 i# H, t8 o4 _
5)  $all
3 }9 D5 o- z& O6 x
; S6 B* N4 Y7 q0 p# p- E0 W$all和$in类似,但是他需要匹配条件内所有的值:
, z, }; O, P5 Z% s  d7 X0 W" a9 D% l" Y8 i
如有一个对象:6 V- D" a7 K) F2 G; i1 e
  1. { a: [ 1, 2, 3 ] }
复制代码

# Y5 y3 I! ~9 X- R5 x& S
下面这个条件是可以匹配的:
  1. db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码

( R: ~. m, [: {+ W3 [
但是下面这个条件就不行了:
  1. db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码

- D9 T& h. l$ g6 C# W) b. c3 K2 f
5 L# b) h" m7 ?- d. }* x7 _
6)  $size7 o$ F, y) b5 h, \

% K+ [. j! Q+ S$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:( U) Z' \3 M. `
4 Q4 I" X$ n9 S9 Y6 G' x) |, d# E
下面的语句就可以匹配:
  1. db.things.find( { a : { $size: 1 } } );
复制代码

  A' M( y) `5 K. U! X8 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.
" Z, c/ \; \2 x
7)$exists
$exists用来判断一个元素是否存在:
如:
  1. db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回7 {5 ?  r9 a( Y3 e# q
  2. db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码

: _2 U, p3 |2 H5 N3 O/ W
8)  $type
$type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。
  1. db.things.find( { a : { $type : 2 } } ); // matches if a is a string1 l8 X# ]9 y; C# j
  2. db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码

  H' x/ j1 `  c
9)正则表达式
, o% A0 d+ f1 Z8 G! U( N8 U
8 U# O' }4 Z# f( T* f  W7 d) `) ?" Pmongo支持正则表达式,如:
  1. db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码

9 p4 X5 Q) V6 D  _& W+ T6 n
10)  查询数据内的值
) d5 K- y/ J  O" a, E/ ]
% w$ v' N1 v. K4 v+ o- h( S/ s下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。
  1. db.things.find( { colors : "red" } );
复制代码

% S3 ~' G% L5 N4 N/ s: J* n& M8 O
11) $elemMatch
+ v5 Q* L7 D; H# V. N  E
2 G9 o$ l$ ^9 }+ B0 E; j+ L  `如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素:
  1. > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
    # N- x8 b7 g4 t$ q
  2. { "_id" : ObjectId("4b5783300334000000000aa9"),  
    3 @, ?$ [1 N  p; q
  3. "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
    / h+ s" t( V% u( t- G
  4. }
复制代码
3 o: [* R- P/ ?$ f; b. T, o- [
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。
注意,上面的语句和下面是不一样的。
> t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
4 Q9 q8 Q; j. t5 }9 B1 C. h) ^0 m
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 8 E0 N6 @! t5 y, H2 t

1 _  s7 Z9 ]' x2 ]! f9 v2 G# f12)  查询嵌入对象的值
  1. db.postings.find( { "author.name" : "joe" } );
复制代码
; R$ z4 W4 ^1 J9 u2 {/ w" U
注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation
举个例子:
  1. > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码

& [+ P% s3 Z) M% A' f/ c4 _1 Y/ |
如果我们要查询 authors name 是Jane的, 我们可以这样:
  1. > db.blog.findOne({"author.name" : "Jane"})
复制代码
$ c: V3 ^3 V+ w% a) c( p8 V
如果不用点,那就需要用下面这句才能匹配:
  1. db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
  t9 C; L$ v4 e& h
下面这句:
  1. db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码

( d8 i. |: I, D3 f. j1 P
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
# S0 B. R, I  k/ c/ \; v
13) 元操作符 $not 取反
如:
  1. db.customers.find( { name : { $not : /acme.*corp/i } } );0 W+ ~  Y2 }- m
  2. db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码

2 c1 o0 x0 |; Q* |
mongodb还有很多函数可以用,如排序,统计等,请参考原文。7 T. \2 x& |2 w7 I+ x' ~& v" @

7 k, b3 ^7 L! T9 P: nmongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接:. w. Q5 [8 N; l: A: \# K) U$ z% Y
  n2 R' r$ h8 T' t4 f) Z
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions% w& [& |1 W# {6 o8 n

& k- s2 {& \- R# I. [版本二:
8 b* I% ?/ j) b" o! a6 P6 a. f
shell 环境下的操作:
   1.  超级用户相关:
         1. #进入数据库admin
; J( d$ R: i* W( P+ y+ i
  1. use admin
复制代码

7 C1 D% Q( u! s1 ?3 @2 c
         2. #增加或修改用户密码
  1.           db.addUser('name','pwd')
复制代码
0 T6 a9 ^' Z/ `7 x' j/ {
         3. #查看用户列表
  1.           db.system.users.find()
复制代码

3 n/ Z3 A. _3 B+ ~
         4. #用户认证
  1.           db.auth('name','pwd')
复制代码
% a# Q/ u: t, B$ Z+ m  k9 R
         5. #删除用户
  1.           db.removeUser('name')
复制代码
0 t& U% b. R0 S# q" M& m
         6. #查看所有用户
  1.           show users
复制代码

/ a0 L( N8 ]3 ~& N! F+ [0 Y) U8 v& g! ?
         7. #查看所有数据库
  1.           show dbs
复制代码
( N2 D% j* A; s
         8. #查看所有的collection
  1.           show collections
复制代码
# R! h* T: y. J- @1 ~7 A' i4 k) l* X
         9. #查看各collection的状态
  1.           db.printCollectionStats()
复制代码

' M* I1 e  d! d2 j/ s
        10. #查看主从复制状态
  1.           db.printReplicationInfo()
复制代码

# z2 u) R  |7 m, E
        11. #修复数据库
  1.           db.repairDatabase()
复制代码

' }9 L3 D# w# e) q/ r
        12. #设置记录profiling,0=off 1=slow 2=all
  1.           db.setProfilingLevel(1)
复制代码
9 I  h9 s/ q5 a" D% b  E
        13. #查看profiling
  1.           show profile
复制代码
: j. H% Z2 a- q! J
        14. #拷贝数据库
  1.           db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码

# E6 z  C+ o6 {. @
        15. #删除collection
  1.           db.mail_addr.drop()
复制代码
  I7 t& t; l% r$ Y  Z4 R
        16. #删除当前的数据库
  1.           db.dropDatabase()
复制代码
7 V7 n) p  t( M; A. p! j
   2. 增删改
         1. #存储嵌套的对象
  1.              db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
# ]* {" O- [0 P( {- [% @- }
         2. #存储数组对象
  1.              db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
/ h( B% l& f/ O3 S9 k) S! [
         3. #根据query条件修改,如果不存在则插入,允许修改多条记录
  1.             db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码

3 L+ X: A" ^# k8 P- D# f/ T
         4. #删除yy=5的记录
  1.             db.foo.remove({'yy':5})
复制代码
$ r5 W# f% V2 u9 s( ^3 ]- [8 K$ j# W8 p
         5. #删除所有的记录
  1.             db.foo.remove()
复制代码

+ W6 Z- @3 M6 n
   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()
2 n) h9 p7 }5 v$ H* ]  i& {5 b
6.  高级查询
条件操作符
$ v9 a) V2 m2 E+ {& X+ Y% s
  1. $gt : >
    ' z" [' R8 S, K4 Y, [" s( ?% @! x
  2. $lt : < * s0 ?; _) z$ A' q8 s# E
  3. $gte: >= 8 ~, n, E* j8 ]& L( d8 X
  4. $lte: <= 7 }( o5 f0 n% h: H
  5. $ne : !=、<>
    % m2 Z" G; y6 t: x2 K
  6. $in : in # Y% I) d% }6 g+ b" ^9 }1 @5 I
  7. $nin: not in : e( ?5 Y# c* r! [% M) T/ D8 R
  8. $all: all   w( N& C' V; n- H1 ?  t* z, \
  9. $not: 反匹配(1.3.3及以上版本)
复制代码
5 D$ B; a! o- C! V+ U, O9 M* a3 v

7 J& Q& Y8 W% y2 N1 f. s0 Y查询 name <> "bruce" and age >= 18 的数据
" _& |1 y( Q% v0 q, l- l4 ?
  1. db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码

4 _  Y/ \! l; H2 w/ Q2 O& z4 C- k% n) U9 [4 j/ K/ v. X3 m
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
( a  @. ?% p5 m+ Q4 o
  1. db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码

- q$ N3 I) q' L1 ]1 @% N1 L! R7 ~8 M+ h3 s; C- u
查询 age in (20,22,24,26) 的数据
4 E3 o- h7 W! ~* v7 Q  k5 C- Q
  1. db.users.find({age: {$in: [20,22,24,26]}});
复制代码

# b/ s# O0 Y3 n1 k# g
5 ]9 F. g* w) @3 ~查询 age取模10等于0 的数据 " P) e- H8 s6 _( A2 w# h
  1. db.users.find('this.age % 10 == 0');
复制代码

# q7 F) ~7 m2 x4 c或者 4 `4 U% w# t( R2 E: W
  1. db.users.find({age : {$mod : [10, 0]}});
复制代码

  z  X* c) \8 y% g0 a0 U$ O2 V$ L. c' `( B7 r7 F6 l8 a
匹配所有
% e$ k3 a" J# Y/ C+ [9 r  I
  1. db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
0 X8 B: o9 i8 h" @# h" \
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } ' i# O! d4 H: j" Q' [
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
% T- ?, N4 n0 z! n
7 \8 S, [( t. ]$ M查询不匹配name=B*带头的记录 & ?: W5 r* J1 h$ l( e% I$ }4 o
  1. db.users.find({name: {$not: /^B.*/}});
复制代码

1 O) u' B- R" O查询 age取模10不等于0 的数据
! |+ k. t+ h2 @
  1. db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
) ]+ J2 g" R+ p

/ W5 g: W3 _: x#返回部分字段
" T, F' a3 V" [3 u/ g- Q选择返回age和_id字段(_id字段总是会被返回)
! T4 Z7 o  A) Q! w
  1. db.users.find({}, {age:1}); 8 Z9 r) ]( \2 W; l' _
  2. db.users.find({}, {age:3}); & b) A# W. n! a- X: g
  3. db.users.find({}, {age:true}); 6 O. Y* @) ?4 H/ C
  4. db.users.find({ name : "bruce" }, {age:1});
复制代码
, ]3 j9 K# @; S: K4 b+ c
0为false, 非0为true 9 k$ e% X# @9 c9 G% s0 ]( ~1 V
) i% g! s4 k+ f/ |
选择返回age、address和_id字段
) o' G7 G9 d* o; c& }. e
  1. db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码

) h$ m) ~; C; o. @! v  ^
! E/ O8 Z$ D0 t/ b& ^排除返回age、address和_id字段
; |7 q6 `9 S* R; M
  1. db.users.find({}, {age:0, address:false});
    ) r7 x% B3 }9 r3 \- I/ j) w
  2. db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
+ V6 E  X5 j+ m$ U0 U9 A
% q6 Z! Y- [# i8 x6 ^
数组元素个数判断
6 z' l7 Y/ V$ l  s: i+ h1 @; `8 k/ f对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 1 a- @7 p5 l! Q
匹配db.users.find({favorite_number: {$size: 3}}); ( \6 [, [. j' {' ^3 W8 Y) e  U
不匹配db.users.find({favorite_number: {$size: 2}});
& P5 O8 R+ L: k+ u( |' k  s/ i. A5 ]9 c5 r3 f
$exists判断字段是否存在 # Y5 W1 r- a' s) B
查询所有存在name字段的记录
0 L- e2 x2 _1 y
  1. db.users.find({name: {$exists: true}});
复制代码
/ r: ]. U5 s# @- }8 ?
查询所有不存在phone字段的记录 2 \0 u0 w2 s9 G9 e
  1. db.users.find({phone: {$exists: false}});
复制代码
; d2 A( ~& p& g4 j
! k& d, D# Q- K+ u( a
$type判断字段类型
) V( o' E9 f; B2 D9 R查询所有name字段是字符类型的
9 N) P  k. M$ s3 k$ A
  1. db.users.find({name: {$type: 2}});
    , @6 @% q5 _) E" `( O# Y+ W2 Y
复制代码

# P; ?( B( C" D* _2 s查询所有age字段是整型的
5 b2 _& E2 t/ J% ]; S3 y
  1. db.users.find({age: {$type: 16}});
    + m5 g' |' _2 X3 b/ Z% _
复制代码

7 _) P# ?; `# q对于字符字段,可以使用正则表达式
# M1 L! q* P5 Z/ \2 p: p查询以字母b或者B带头的所有记录 " H$ K  y7 d0 C
  1. db.users.find({name: /^b.*/i}); 5 l! g. k. g( o5 P$ Z; |" m! p$ i5 k: w
复制代码
. ]/ r* w0 O1 [/ g, `0 V3 e
$elemMatch(1.3.1及以上版本) 0 @3 n7 Y$ q$ z# `1 G6 _
为数组的字段中匹配其中某个元素 7 c' L2 }. Z# H

) p& d; I2 _% ~% x# PJavascript查询和$where查询
; C0 n9 W. j' L* j! h# C查询 age > 18 的记录,以下查询都一样
# T- z& W7 z$ k, B9 C* U
  1. db.users.find({age: {$gt: 18}});
    . k) \9 d9 C% h1 t9 Q
  2. db.users.find({$where: "this.age > 18"}); * h; J% F2 K  Y9 j3 o
  3. db.users.find("this.age > 18");
    1 L; R* v0 X8 L  h, y% |3 u7 j9 A
  4. f = function() {return this.age > 18} db.users.find(f);
复制代码

. c$ H+ J# ?7 I2 Q4 `/ _  C) N4 T6 ?: t( m# [3 \9 @" |
排序sort() 7 j1 R0 n+ i$ f7 f
以年龄升序asc
7 C% _- R! T( t) S7 |+ w' @
  1. db.users.find().sort({age: 1}); 7 U$ x5 K# c+ i, f+ }3 S, z, Z
复制代码
& n. M. B8 u1 q2 [% W8 h
以年龄降序desc
5 v1 S$ `; Z4 P3 V, J0 a  N8 k3 P
  1. db.users.find().sort({age: -1});
    7 F! A% v/ R% o: b' b: I) @7 I
复制代码
5 j1 }& \2 D1 [5 h) D- N; S
限制返回记录数量limit()   O( }% ^1 h! |- J( D/ j) ]
返回5条记录
" \1 H$ g( ^$ f% B
  1. db.users.find().limit(5); 6 }7 q3 q+ L% ]$ u' G0 l) h+ x+ e6 i
复制代码

1 }8 U3 t7 J6 S  J返回3条记录并打印信息
2 y- j+ A. j9 ^; E. b/ x/ c
  1. db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
    1 h$ i+ b! T, W& A+ M
复制代码
; U  g) Q1 i) p
结果   g/ y8 G2 l5 J. V- {7 M
  1. my age is 18
      n+ m" Y3 B0 v6 b$ q% `( O
  2. my age is 19
    3 {8 l# \2 Q; A+ g
  3. my age is 20
复制代码

: n$ b7 M' @) }6 x% N/ }, k% Y: x
6 ~0 e+ F0 r8 V. `限制返回记录的开始点skip()
! R7 X& b& X6 _. C0 M( }从第3条记录开始,返回5条记录(limit 3, 5)
2 G$ I1 _8 R: }- b, Z' w
  1. db.users.find().skip(3).limit(5);
    * [0 U2 ]) k* q
复制代码
0 V; ^9 @. U8 Z' l2 Z3 S% V/ \' f
查询记录条数count()
- q* y$ X* H& l# [: x- U8 ?db.users.find().count(); 3 U  @+ Q( M, w( c
db.users.find({age:18}).count(); * g: c& e1 {7 Q0 d; O( s7 X" x; p
以下返回的不是5,而是user表中所有的记录数量
3 s  o! t$ V- gdb.users.find().skip(10).limit(5).count();   ?) A) N' \1 ?! k; W
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
- o/ v4 N  \1 m- x9 ?0 }, {+ `8 W
  1. db.users.find().skip(10).limit(5).count(true);
复制代码
6 a4 |8 h" `( i: M6 g
4 H! @; V! b: e& g' S
分组group() % B" M5 C$ y0 o  v+ j
假设test表只有以下一条数据
2 {* f: F4 \& m  m5 A4 F  z  i( m' T
  1. { domain: "www.mongodb.org"
    ( [( x. l# S  [) w: S7 Y9 P8 `
  2. , invoked_at: {d:"2009-11-03", t:"17:14:05"} & L) Z' y" x1 ~. \6 J/ A
  3. , response_time: 0.05
    ; O. J: v  R6 L5 }" M
  4. , http_action: "GET /display/DOCS/Aggregation" " O$ t& \  a: W% \! z9 w
  5. }
复制代码
1 `3 r  u0 @5 `8 [% b% m3 \
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
/ p5 W$ m4 F+ r! S% Q3 i7 R' M
  1. db.test.group( + W+ N# g3 i; }/ a1 k" P
  2. { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} 9 }: q9 W( c4 Z! F& R; O
  3. , key: {http_action: true}
    ! r9 E2 l+ D3 {; X
  4. , initial: {count: 0, total_time:0} * w5 Q) P% `& X' S1 k
  5. , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
    4 z: m: B2 c$ }+ Q, \- ~: c
  6. , finalize: function(out){ out.avg_time = out.total_time / out.count }
    % r2 P9 I1 [7 |8 Y* p; w
  7. } ); 5 r* E5 v' O8 A* c7 ?* x3 d

  8. & s# k/ P( r9 w2 @- e" v+ v# D
  9. [
    3 p; F' x: _% |, O+ `! q- @; N
  10. { 8 H- p4 l# `, ]( ?+ T1 I- p5 x7 c
  11. "http_action" : "GET /display/DOCS/Aggregation",   I1 |& n5 S( d; y
  12. "count" : 1, " J8 @, j' H' b6 G
  13. "total_time" : 0.05,
    # V- c) h8 a6 u7 \9 p6 |0 i6 Q
  14. "avg_time" : 0.05 & O) z, q5 P) Q/ P: J# x; z. b
  15. }
    0 }7 O! m( ^! r1 D
  16. ]
复制代码

* d9 [4 o5 I1 Z2 ~- X/ V4 {# ]+ F  Z; e# \+ r8 i% V$ h3 S

( I0 E; i- X$ M8 gMongoDB 高级聚合查询
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
    : [- \) Y$ K+ A2 f0 e- `, U
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。
要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。
如我的例子,我想取得集合中年龄最大的人。
  1. db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
" R! {2 o. U2 E! }
$ A$ @0 W/ J1 ~+ |# O; v+ ]
1 y* z$ k$ n4 ^! o& I" s1 |
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。
当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits].
如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。
如上面的表结构,我想统计所有的喜欢的水果。
  1. db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码

* B& t0 e7 x; v" U% q4 w3 L  ~1 B
他成功执行了。输出如:
  1. [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
" W- q3 ?) G  K, ]

$ M' B% F7 g% W' X  j4 |) E
我想统计集合中共有多少个人[按名字吧]
  1. db.person.distinct("manName")
复制代码
! w# Y6 E4 V* i( `! \9 E

' N+ {" o' z. _7 d
我想统计指定个数的人的共同关注的朋友。
  1. db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码

, Z+ |* d1 S+ h4 d& ]1 m: y
+ k/ K8 i! u$ b! H0 i, C( Y# @
输出如:
  1.         
    ; s3 @/ n: ]) {2 s" r2 w  S( h8 l
  2. [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码

$ I4 Q: G, [1 S! v& K7 E* t  \7 m& o* ^4 E' r9 q
5 k9 B2 x' q( B: D4 {  [4 d
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的?
Spring Schema:
  1. <beans xmlns="http://www.springframework.org/schema/beans"* Y( m% [! G+ a; o7 A0 D5 n3 q
  2.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5 p+ y! ~1 B. L. F9 Z3 P
  3.        xmlns:context="http://www.springframework.org/schema/context"( ~" p4 T! a& X# o0 x
  4.        xmlns:mongo="http://www.springframework.org/schema/data/mongo"
    * i( d2 u( e) u. H& H# r/ G- j
  5.        xsi:schemaLocation="http://www.springframework.org/schema/beans# r3 m' k* t5 x; f/ B) k! A
  6.           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    7 ~1 R9 \# V4 J1 R
  7.           http://www.springframework.org/schema/context* k9 j, P4 X; _" p
  8.           http://www.springframework.org/schema/context/spring-context-3.1.xsd
    " h# v" M0 e2 w: w9 H
  9.           http://www.springframework.org/schema/data/mongo! S& |7 E2 [- e0 D# e% C
  10.           http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
    8 a/ r. l- t* F$ p. m

  11. ) N- {, F! R9 ~( w
  12.     <context:property-placeholder location="classpath:mongo.properties" />
    . r' e& k* l# A" F3 M+ x. O3 U
  13. ! w9 k9 {* D5 r- j" ]! O# {
  14.     <!-- Default bean name is 'mongo' -->
    * t$ T' S" a/ X  N% e' F9 z! [
  15.     <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
    9 R7 U$ W) _  `* v+ p: A
  16. * A! w8 v! o" K6 S7 Y) E
  17.     <mongo:db-factory id="mongoDbFactory"
    4 c( U0 j7 E. q
  18.                   mongo-ref="mongo"
    * F0 G6 J, a; V$ d! D6 l$ {
  19.                   dbname="mongotest" />4 p- T/ M( w' L8 T& Q6 ]# V$ l

  20. / J/ Y, o9 P5 x
  21.     <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
    7 X+ \! L$ ]+ N7 S4 G& s; b
  22.         <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>1 V' H3 s* S6 |! t# }" X
  23.     </bean>
    ' n* w6 m  v1 \# v0 o, E# B
  24. </beans>
复制代码

- [  z4 {9 k/ J: S
2 Q" i- J+ s0 M$ L
maxmin的测试
  1. @Test, P' l: b( V; a2 Z
  2.     public void testMaxAndMinAge() throws Exception {
    % i  Z/ S& y/ \$ K6 d8 ?
  3.         Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
    : |3 t0 Y, y6 f/ a% {. e
  4.         Person result = mongoTemplate.findOne(q, Person.class);! j' S$ H7 y% n
  5.         log.info(result);4 {4 H( W, l, B2 P
  6. ; p2 `; y/ W# d6 u; a5 X" O& M
  7.         q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);/ X1 o6 W! R! Q' G9 g- ?
  8.         result = mongoTemplate.findOne(q, Person.class);
    * q1 k# E+ Y' Y  u
  9.         log.info(result);- `0 r1 i  r! ~% p  n' y
  10.     }
复制代码
# f: m8 i( g0 H# V% E+ O
! {, H5 H4 F5 L' f# ]! T0 L9 f' C
distinct的测试:
  1. @Test" H1 w& h9 L0 O$ C
  2.     public void testDistinct() throws Exception {0 M3 M4 a) M! A4 _7 L1 [9 o) f2 E/ z
  3.         List result = mongoTemplate.getCollection("person").distinct("myFriends");
    4 e9 h$ \: j/ o! @; y+ [7 v+ S* ^
  4.         for (Object o : result) {/ j: N. {8 a% Y% b+ v5 _/ b
  5.             log.info(o);# V9 Z3 k& b) T+ ~. X. F# s
  6.         }
    ' U7 \; P) F  g/ v5 k/ J

  7. , t: a7 i& D, L' ?
  8.         log.info("==================================================================");
    2 X$ ]! b( ]  g- u0 b7 P2 k. _. [7 G
  9.         Query query = Query.query(Criteria.where("manId").is("123456"));, ]( _  K% F) S8 Y% c9 N. q
  10.         result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
    2 ~) J; R4 n+ ~9 i  C7 C
  11.         for (Object o : result) {
    ( U! s& G8 c/ Y. ~' D. z9 g) N
  12.             log.info(o);
    * @8 b! I3 a% K/ Q4 b2 W
  13.         }7 M: D1 D) r6 J0 r/ Y6 k

  14. 5 B3 y  g, H9 z; q
  15.         log.info("==================================================================");
    5 z9 O6 U" @/ f
  16.         result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");2 m2 p) \9 H. ]: C1 s; t, [
  17.         for (Object o : result) {
    9 ^6 }( Z: r- ?8 j5 F4 U
  18.             log.info(o);' x% {: i5 w" y7 @2 G9 n
  19.         }4 V( B' E3 A% e  q/ {/ |4 `0 M
  20.     }
复制代码
# T6 J# ~4 Y$ [) a- v" R2 {2 S. W) ~
4 O) [! H8 B! P0 Q, G6 r4 N
输出的结果为:
  1. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
    % a, e& `5 l; F* i
  2. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678! X; ]: \+ T$ v$ M4 T
  3. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789, k3 m% X+ Y4 v
  4. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654. m0 a# ]4 z. |8 C: E9 E, Y
  5. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
    5 ~, }- i! Q6 Y% v- J; Y3 d
  6. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo  V8 z7 e/ r5 ]8 F9 e2 R: R
  7. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
    + ?- n* n& N; r
  8. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================) ~6 q3 N! m  B
  9. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
    7 x( r6 M: N7 M# i
  10. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
    2 e* X% e/ ^7 `' C# O
  11. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789/ ?' q7 B, z8 I
  12. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
    # P, Q6 T& d: V* c: _0 b
  13. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================6 ^* n# a: e' Z* t0 f
  14. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa4 y! F+ j6 X. N0 p2 V; @1 i
  15. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
    2 B5 n9 K' U8 G. W
  16. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
    1 }5 d: W* Y1 X0 Z& S7 ?3 o
  17. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www* ~" b+ ~0 ?% w2 G( O. z" l; l
  18. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx4 H9 Q8 A- U( [5 M
  19. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
    0 z9 L' {  e/ j! \
  20. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
    & @4 k) V1 Q* a  M* \; N: Z
  21. 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr: k3 q8 D* A$ t. g1 [& D
  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
复制代码

5 Z- G$ c6 J$ u: W' R0 R, W0 |2 {2 t6 Z) ~3 A& T8 S6 P
这里我要特别说明一下, 当使用了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等信息。

1 c/ R  k  X6 P9 M- l- f' V* H& `* A; w3 r6 b" T
! f% f: U8 G1 r* u$ d1 \





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