版本一:7 z. r/ U9 s6 g/ D5 _: C
+ \; S5 r% y. z7 \
1 ) . 大于,小于,大于或等于,小于或等于
5 o, {) u b) z: p) f9 U, X4 T* n W1 Y
$gt:大于
, @, M: P" F9 F$ o9 \$lt:小于
' q" }" O, w/ }6 J0 A2 }$gte:大于或等于
. W! u% ^) O, M+ H% O6 R( h, A$lte:小于或等于
- Z( i9 m) ~& c( {! j* f
' ~, Q3 V7 \ A. S( v例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
, M5 @+ C& b7 f7 n# |: H, } - db.collection.find({ "field" : { $lt: value } } ); // less than : field < value4 c6 }5 z/ D" G
- db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
( O/ y# X+ v5 M/ g' M0 _ - db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码
7 |! _ ~" M- r& i7 n如查询j大于3,小于4: - db.things.find({j : {$lt: 3}});' g* Y' Y2 l, y7 M# z
- db.things.find({j : {$gte: 4}});
复制代码
o3 Q9 d0 j z* C) {# _5 j也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码
" e5 N N( R* k' I
P8 I$ k% k4 {) |/ h) F8 B4 q7 l Z7 w. |7 W
2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码 8 z/ i ]0 X' S
3) in 和 not in ($in $nin)
. n# d- D. ]/ o" b* l( ?3 l) ]) z% J6 d+ i+ B. s% R: v9 j+ R2 o
语法: - db.collection.find( { "field" : { $in : array } } );
复制代码
+ o. x" _# K; c6 p7 n( J H例子: - db.things.find({j:{$in: [2,4,6]}});' y$ n; }: B# ~$ Z! @# ]7 F
- db.things.find({j:{$nin: [2,4,6]}});
复制代码
! g- f$ a% J5 h; L: v1 }
$ F$ D# C3 @4 e4) 取模运算$mod
9 M$ L* Q6 c- R. y) W; W H. i4 [
f3 H7 l4 s M( g如下面的运算:
- db.things.find( "this.a % 10 == 1")
复制代码 0 E. y# I" q9 B6 o" p' Q" @
可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
% c+ A/ B! C6 q. D$ J, f6 f$ @! L
/ o8 y3 a8 |0 ]* H5) $all
- J: I: |; ^" v" T% ^: u' i6 A5 [% P/ |0 Z
$all和$in类似,但是他需要匹配条件内所有的值:* {8 Z0 @2 u% b; D1 X7 L, f
# C. V5 t* r- T2 H1 i9 I& s1 G
如有一个对象:- F7 n- Y$ D' y0 R
8 Q( [! {/ L# ?: m! K
下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码 % |9 r9 a$ l+ s6 P; }6 L) @% L u
但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
. }/ \# [. k& j& D/ T& g3 |/ y6 z8 J+ g+ I6 s1 U
6) $size* o: t2 _8 a" \2 A, Q
1 k+ U( R% f: u" g+ g
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:8 x5 \) e5 p- L" B* H; ~( V
# w+ S6 ^8 @4 H o: G
下面的语句就可以匹配: - db.things.find( { a : { $size: 1 } } );
复制代码
3 G, e! X$ P$ d官网上说不能用来匹配一个范围内的元素,如果想找$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. * Q5 | ^) r1 b4 d
7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
. N2 m% j, ^; U0 |4 t - db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
, J1 \1 M1 y5 H6 `) q8 C8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string+ ?, T. ^% k" u+ P4 Z; l6 B/ W
- db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码 ^6 {7 m# g Z$ S
9)正则表达式
. A$ S+ U9 f7 N3 r2 ^7 {0 x
2 E2 q4 g9 p/ K; dmongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
- P9 a. R+ w6 s$ J; s# L% D10) 查询数据内的值
( b/ \7 ?8 ~, }6 I7 l
# ^8 Q2 {2 I( T6 T9 _4 A下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码 & G: m/ H+ W& d& A
11) $elemMatch
3 [ a" e. F& _6 m
1 o7 M* u1 W6 M% @. ~6 i) L如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) 6 s6 n# Z' k7 J( ]7 p! N- S4 D
- { "_id" : ObjectId("4b5783300334000000000aa9"), 4 ]) C4 @8 \2 K$ d: K
- "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]8 c7 _0 {$ ~3 W# _5 D0 e! O
- }
复制代码
# f; l, t1 ^0 e1 e5 u9 k$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
0 w a1 t# O: j4 q. S$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 2 h n$ R4 R. \0 G. I6 O3 R! ^; {4 w
( a1 c" s, B3 Y& U/ Z, D2 D; a, }
12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码 # }8 }# R6 C( l8 ^& A
举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码 3 [% I3 ^! E2 O7 d- B
如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码 1 J1 u: B! {6 S3 T5 {/ P: Y; v
如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码 + p5 ]( F# _% d, z
下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
* c, u; E3 ~; d8 _, B是不能匹配的,因为mongodb对于子对象,他是精确匹配。 3 x" `/ d% {- Z; ~2 `% M1 U
13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );
. y" o( C% Q6 A( B3 S" L" |. Z - db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
) x8 c2 b6 z0 k' w+ }9 bshell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin
( L8 a! ~1 _3 F
: t# i9 T! n; O$ j 2. #增加或修改用户密码 3. #查看用户列表 4. #用户认证 5. #删除用户 6. #查看所有用户 6 o$ S8 _) W j5 b3 G" z" p
7. #查看所有数据库 8. #查看所有的collection
! _4 S6 l, c6 J2 h3 m& [1 E/ b 9. #查看各collection的状态 - db.printCollectionStats()
复制代码 9 n0 d" g6 L' `" C2 q
10. #查看主从复制状态 - db.printReplicationInfo()
复制代码 $ F$ U8 }9 k8 U# L6 {7 Z
11. #修复数据库 12. #设置记录profiling,0=off 1=slow 2=all 13. #查看profiling
7 v6 l' r- e$ k) x a$ H' c) n) k- e 14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码 4 b' @3 x! L. m( Z/ o; x
15. #删除collection 16. #删除当前的数据库 2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码 4 ~( s$ `' T# B1 g" ?" ^
2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
* F9 {: d# r. S. I4 _8 w# L5 I 3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码 # @3 m8 M- O, t# j; g! T9 W( t
4. #删除yy=5的记录 8 T0 D% X% S8 z4 j3 l, Z9 [
5. #删除所有的记录 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- @! f7 b8 u! W8 R6. 高级查询 条件操作符 7 E& Z* Y% z$ D. X% k* X C( n: n8 z, M
- $gt : >
7 \+ r7 l; Q' h: a4 ~5 g. L - $lt : < * a" u3 V! a8 G$ y1 ?, ?: J! Y( l- ?
- $gte: >=
3 S7 k$ e9 W' ~4 s% k - $lte: <= A) M3 P2 ]9 ~7 w+ G' H; P# _
- $ne : !=、<>
9 U8 s' o7 O1 K9 t' ?' ~ - $in : in 3 ~; p2 F* y- u/ P+ ?
- $nin: not in
; Z3 U; Q& G" t( P n5 m* {& \ - $all: all , \) i- q0 r6 O7 k* ?1 M( Y
- $not: 反匹配(1.3.3及以上版本)
复制代码 / g! o2 c, M/ R& X
6 m2 x( Y3 O7 b* o' [' L
查询 name <> "bruce" and age >= 18 的数据 ; A$ [0 Y, I! H
- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码 8 z& d& V# _: i) f$ f7 T
L6 I" h9 `- Y* K8 z" Z7 y( u
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
" e9 y" f7 d: C; ^- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码 6 P$ i+ V+ K4 |9 \* H& S9 E: U: S
" n8 Y; b' m0 }/ B
查询 age in (20,22,24,26) 的数据 . ~' i- N/ L, X3 W. d! O# p c
- db.users.find({age: {$in: [20,22,24,26]}});
复制代码 . h3 M8 ]$ \* c, @! k. o
* Y3 X V: m, t. M查询 age取模10等于0 的数据
0 r1 f x5 z5 Z0 v: G% ]# x- db.users.find('this.age % 10 == 0');
复制代码
. d# r$ D1 }) p( ]# }或者
1 Z# d! Q6 p: G/ j8 l- db.users.find({age : {$mod : [10, 0]}});
复制代码 9 Z- @+ Y! V6 G/ n+ B3 E# E9 _) d
4 K5 b5 h9 Y$ Z+ t! ^/ z. ~
匹配所有 ' m, v- F( L4 x; }7 n
- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
3 g! L6 A7 ^8 C. G1 E可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } : @; E9 O, Q0 S0 F4 y2 l
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
b g4 P F5 e. @( l' Q& J- ~5 R: Y g# Q. D' A
查询不匹配name=B*带头的记录 * r* e0 E" ~6 v7 L+ I
- db.users.find({name: {$not: /^B.*/}});
复制代码
& {% x Z/ J/ r: U+ D- S9 C查询 age取模10不等于0 的数据
0 f: J8 S' V6 f. i/ q) D3 v1 U- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码 $ w+ J2 |+ a+ g; F* ^1 K; Q; k
8 f# p) O/ ]" [7 c5 h/ I; N- C#返回部分字段
- c- u z [" S" h9 L( W选择返回age和_id字段(_id字段总是会被返回) 6 e1 C; i* J6 Z' h3 n1 s& n
- db.users.find({}, {age:1});
- z9 ]- p5 ~4 B0 {' \+ u$ |( X1 x - db.users.find({}, {age:3});
! l' ?. A3 z- I a! Y7 R5 w; }, N9 f - db.users.find({}, {age:true});
; p9 C( Z$ [: d+ [# s l7 p5 U* t) h - db.users.find({ name : "bruce" }, {age:1});
复制代码
+ P: p) O' m& t: k& C2 b8 h1 ~8 d9 g* \0为false, 非0为true
; o9 b7 P4 I' M+ ^0 f) `9 N+ d5 D. ^3 C
选择返回age、address和_id字段 2 d- p; ] s I- K
- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码 . ^4 L% S' j5 J- _. I
6 n/ r" K% n9 {; {- d
排除返回age、address和_id字段 ; V2 M6 K5 {1 O! _* F- ^
- db.users.find({}, {age:0, address:false});
8 v% M& g, C; [# P6 Q2 v. \+ k8 f - db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码 6 b+ d/ J- a9 |* s! k
) [3 P1 R |5 Z. g
数组元素个数判断 # N, K1 l2 `+ \+ u/ j' m5 M
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
* M2 q0 U* Z6 q9 J* Z3 L9 o# g匹配db.users.find({favorite_number: {$size: 3}}); , f6 f) c: F. a3 x7 E3 J- B
不匹配db.users.find({favorite_number: {$size: 2}});
& U [: V6 y, s
' o$ _1 |+ S u9 m; _# v+ B$exists判断字段是否存在
' C2 X2 D9 a: Q# O2 h' e查询所有存在name字段的记录 ) h K6 l( U# H( k
- db.users.find({name: {$exists: true}});
复制代码 5 e1 k: R% c) H
查询所有不存在phone字段的记录
! L1 H2 B! n+ Q: }+ ^0 a* J2 k- db.users.find({phone: {$exists: false}});
复制代码
+ t4 H" o: a+ V- d/ `$ ]6 Z, X, s1 O2 g2 i: f: N
$type判断字段类型
3 |3 H- ] u9 u: [2 p查询所有name字段是字符类型的
2 @; x t- |* y! R- db.users.find({name: {$type: 2}});
0 g( U# C) b, f' e# q9 Z. Z! q
复制代码
" n/ A- U0 y/ I$ D% a查询所有age字段是整型的 3 h/ D4 i4 y' M! V/ G5 e
- db.users.find({age: {$type: 16}});
# l9 \4 r% P) e$ w; F! }
复制代码
, J; a- I! c4 O) w. ]+ \' E对于字符字段,可以使用正则表达式
" N! e6 r% p' J' z6 |( D3 g查询以字母b或者B带头的所有记录
6 @) l2 t5 J$ U: J- db.users.find({name: /^b.*/i}); 2 \5 w' K' n* Q/ ]( T/ o# a) A
复制代码 7 V: z7 r2 R8 U2 _9 d( @' N' g0 k; \
$elemMatch(1.3.1及以上版本) p3 c8 B0 ~3 T' V/ f4 K
为数组的字段中匹配其中某个元素
& C9 l5 j; a1 h6 ]
' F2 V8 V5 x; H. z5 p8 I& pJavascript查询和$where查询
' I* B: v& b1 K2 z* J- C# m/ k查询 age > 18 的记录,以下查询都一样 3 x' J% k( S2 C8 L6 t0 C
- db.users.find({age: {$gt: 18}});
8 a4 v) j' B; t( } - db.users.find({$where: "this.age > 18"});
, {2 f- }: h; ^3 o. U4 b - db.users.find("this.age > 18");
, V5 d Q5 }, z$ N - f = function() {return this.age > 18} db.users.find(f);
复制代码
) Z+ m) S( z, Z% T8 m* Q# o5 x! O& S6 B6 X0 m i
排序sort()
7 d% x c, X* S/ x& N' w以年龄升序asc
- j; a+ L0 F0 q& i- db.users.find().sort({age: 1});
2 r$ O5 g6 C5 v3 e5 k
复制代码 9 R$ K! Z3 N+ f2 u" A; k4 B
以年龄降序desc
5 `5 Q" ^/ D$ ?" n- db.users.find().sort({age: -1}); ! A# t8 y9 c# V5 h
复制代码
0 y$ H% K. \2 R3 |限制返回记录数量limit() , R% f. Y( }& r! ?
返回5条记录
& c1 j% z6 m, U9 Y- db.users.find().limit(5); % f+ ]9 G3 t6 r! R8 ]8 m, p
复制代码
! d; ]8 w5 M8 P$ F返回3条记录并打印信息 , o1 h) b Q6 D1 s4 {
- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
4 J/ d* G$ s; z
复制代码 ) n- ?3 Z+ V8 ], n# b
结果 2 R$ @, R, j5 w. V
- my age is 18 . i! N( J9 }4 z0 [# `( f
- my age is 19 ) ]3 y8 \! A4 K' h( I) n: e
- my age is 20
复制代码
# J% f p" u5 q( j, I+ O. }
) B+ I8 [2 s- }4 Y限制返回记录的开始点skip() , [$ t) `0 t( E7 @# n- O
从第3条记录开始,返回5条记录(limit 3, 5)
: v% h" ~6 J: X' T- db.users.find().skip(3).limit(5); 1 O( a% d0 s7 w+ a I/ v/ a, P
复制代码
. r7 D4 m. R9 W: s, n, ~查询记录条数count() ' |! ~/ ^8 ]6 }( { m
db.users.find().count();
% i/ F: Z$ p6 P. [3 {db.users.find({age:18}).count(); 6 G7 O7 {& h. d( d
以下返回的不是5,而是user表中所有的记录数量 " f5 P; G. _- z/ D' }% O
db.users.find().skip(10).limit(5).count(); 8 f8 |- ^" j/ }. X
如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 3 X6 E9 x) H$ J( \! e. Y1 [! N
- db.users.find().skip(10).limit(5).count(true);
复制代码 , q+ j: y5 a+ M ~9 Q
* K8 T( u' Y: @0 Q L7 `! O分组group()
O' Y k+ c: C( q" y假设test表只有以下一条数据
0 Z1 b4 ~; y/ N0 N2 T- { domain: "www.mongodb.org" ' w- z- l5 @% d; }( ?) U" e( w
- , invoked_at: {d:"2009-11-03", t:"17:14:05"}
' G5 ~1 c! Q% c+ G9 h! D - , response_time: 0.05 ; ^" J T! R4 v' |$ _
- , http_action: "GET /display/DOCS/Aggregation" ) A4 T! U; q% t2 u
- }
复制代码
4 H% e8 O. Y c使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
- D ` [) t e- db.test.group( ' H8 m! k% R6 Q- d& s8 |3 ?
- { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
* j/ U9 m9 ?. S' n0 u7 k - , key: {http_action: true} 8 v3 N* u# }7 k9 y* o( @ @6 V0 o
- , initial: {count: 0, total_time:0} ?3 r. W5 a/ }8 j
- , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
# a2 V% J, g+ t1 C6 Z! F* ^ - , finalize: function(out){ out.avg_time = out.total_time / out.count } % z% _% Q3 d: U( \% R* {; K% o: u
- } );
( b% x" I% h9 R- v- b/ Y* @
" o3 Z$ ]6 _ ^3 p0 B" w- [ * p9 @, h. n5 t$ f. l
- { - X0 g+ c! g4 H
- "http_action" : "GET /display/DOCS/Aggregation", ; @- H5 Q8 ]+ F2 U2 t, S
- "count" : 1,
8 e9 d0 ~" K' a# x' I - "total_time" : 0.05,
1 A) A% `: c0 w* G$ D - "avg_time" : 0.05 " Z. y, ^$ E5 V" H* J
- }
- ^+ _; C2 J% A) q- r - ]
复制代码 ( M7 P1 i% Z0 j, E, R( ~
( ~9 ~. i3 b/ U/ u7 L( _
5 b9 W& f7 ^9 `6 z% t4 C1 sMongoDB 高级聚合查询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/ U6 F2 A/ {" I. A9 o4 M, P! v
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码 + s7 |0 m' M3 n5 f' ]6 ~! N# g
0 }' O. F5 b- ~+ S" P4 l% v3 h
4 i- B& v6 ]4 @1 W' D2 H% M4 W相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 - distinct! i ?- L- g b" B* W" l$ E. O: `; e
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码 ( c, C6 O! S+ T: Z& r, y% g
8 B2 z- N/ q# Q& M 他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码 7 F. D, l: U5 [- i+ j
; B7 ^7 D* ~5 E0 u2 N9 [
我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码 4 g. u! r' }! m5 y
- ~6 A- c1 S/ Y6 W" t }* W 我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码 ) {1 W; ]; P) t, V! t7 u; L. F" p$ |
/ Q ?" w4 g6 }9 Y& p1 z3 |9 k 输出如: - $ k, }. A& A3 ~1 ^7 O/ C
- [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
3 d9 m0 s @, }+ p$ h- Y2 m; v T% P
' d: H, X2 r1 @3 Q" d4 D9 h: t' q, |7 u3 Y! e
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"1 l9 D/ w6 H! c" Q
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"9 [- M8 n- g, i* h: F$ ^2 c
- xmlns:context="http://www.springframework.org/schema/context"% u5 \+ O# g: v4 i* y; Z
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"* C5 r7 k* H c y1 r, ^
- xsi:schemaLocation="http://www.springframework.org/schema/beans! {: y* ] K: Q( i
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
p _: `) e; n& { - http://www.springframework.org/schema/context% r+ ?$ Y$ q; u7 |4 _4 H+ Y* \" q5 s
- http://www.springframework.org/schema/context/spring-context-3.1.xsd% l7 {9 o" h5 F* x: G/ k- l
- http://www.springframework.org/schema/data/mongo
9 M* ?8 ^* O. M0 f - http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"># ?. V- Z: O$ z! O
-
7 x$ f7 {5 p8 y) I8 d" ]+ W - <context:property-placeholder location="classpath:mongo.properties" />5 U- p' b+ L% }) s1 ?
- - o, [4 s. N4 v+ a2 j, D
- <!-- Default bean name is 'mongo' -->
6 Q* s1 {2 J! a+ V - <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />9 r* o7 {7 i$ S2 Y8 I% f: V
- : ?% y' m# e; N3 J9 s Z
- <mongo:db-factory id="mongoDbFactory"
1 }/ ?/ L0 j* |8 f% y, q2 g - mongo-ref="mongo"
6 k1 x1 ]5 P F - dbname="mongotest" />/ `( p# x' ?) Q" C1 l# K% l
- & v% I6 Z- t& Q
- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">2 I& _7 z4 J$ |
- <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
( @1 `- h9 ^9 f7 w5 {1 b - </bean> ~; e# O5 }9 L
- </beans>
复制代码 ; ^3 ~- m6 K5 x, Z+ K
/ `# R- q2 n& f& [1 G
max和min的测试: - @Test0 v9 m" d& {2 q/ p* S- ]( [
- public void testMaxAndMinAge() throws Exception {
) ?$ J6 l Y* F; W* m - Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
( f5 Z3 i/ e0 u& ^ - Person result = mongoTemplate.findOne(q, Person.class);! }. U) c; v% C; i2 C( u
- log.info(result);
( j; ]# ~! [ f' ~; c: B* l3 | -
2 j- V0 p Z9 a" g5 ] - q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
8 ]% z* Y& X% S5 C; ` - result = mongoTemplate.findOne(q, Person.class);
9 u+ L* H+ q0 O - log.info(result);& a: i: G: z( b! }: M
- }
复制代码
8 c( a+ o9 H t0 J: {0 @
4 B& U4 O u5 s9 p distinct的测试: - @Test
O0 O* }0 W1 U - public void testDistinct() throws Exception {
6 U( ]# m- I- b- I3 N& m4 U# r# n - List result = mongoTemplate.getCollection("person").distinct("myFriends");
. z9 a9 `. Z5 f6 F5 S - for (Object o : result) {
, A& r# \* ]$ D4 _9 ^0 F - log.info(o);
, ~* ]6 ]2 y7 Y; G8 p - }
# r' F' Z; H( o: k* P W9 i9 l - e( K% H" } i- i) f, ^) C
- log.info("==================================================================");9 b& ^( ]0 i) N0 e5 A
- Query query = Query.query(Criteria.where("manId").is("123456"));
- j/ c# H+ A( g. d - result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
! }. d" U2 }& v! ~ - for (Object o : result) {0 S) u4 g% e( l! [* t3 o7 j
- log.info(o);4 M2 Z! a8 C8 t
- }, a: w8 i; I3 S2 @2 E1 @) o
- # R8 [# | ]- Q; K- O
- log.info("==================================================================");. E$ i% `5 s' A, [
- result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
/ \& e1 d) ` _0 r B - for (Object o : result) {) { s. d; Q8 ?) T( y; _ r
- log.info(o);" S* ~. [* L2 Z# n, @9 O5 ~
- }* G4 Z* p, w/ c
- }
复制代码
+ C$ c; [% V- ^( ~6 E+ r1 q& [! h6 z7 j0 e% u
输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567" J5 r3 H6 U4 ]! L
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 3456786 o# P Y4 p5 z0 N8 U$ \
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789; V5 ?- W; p v6 o0 Y8 ^
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
& t( O$ Y7 X( {+ j/ F. c0 L$ F - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni" r6 f' M! z/ u+ n/ Y) ^! O
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
( b- g9 ~$ p5 h% A1 }" L - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
, J" y7 O5 a3 T/ M* | - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================" ]- a+ } n% @. ^. Q3 T, {
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567: }' E6 m+ |$ r, x5 T8 B$ \. O# p
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
& H- S/ t5 a- L' | - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
" d2 J: W2 w/ Y( H* H \6 K' z: e - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654$ ~; i4 L3 o1 v4 |5 z
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================8 S C1 @3 V: ?/ r% n
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa2 K5 B1 P" s( M( _, x& [% U
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
9 c$ j& a! M7 j - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc2 ^7 H4 `* A1 a- G
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www' L2 r& v4 K7 @/ W
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
2 o8 C5 P8 B& o1 m$ m" `3 E2 I - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy x" u: m6 B4 e8 O Z5 t2 K! j0 H
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz8 z. ?) ]6 ?$ F; y2 I3 _
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
' o2 o4 q. \5 c, I, W) k - 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
复制代码 ( `" Z8 a6 W" @8 _! m) ]4 F
7 P2 B9 M* m( _) q: M
这里我要特别说明一下, 当使用了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等信息。
& g, @; H. Q0 [, ?
9 X5 I: ^- q$ T5 [; `4 v
) @8 A& l2 S. Z |