版本一:, C1 G% S, b# r* S
" i4 a% t/ }# c" y" B
1 ) . 大于,小于,大于或等于,小于或等于
- y5 u) i+ K* `% L( f/ i O( F* i) R/ p
$gt:大于
; a( _) s, e+ i4 a- {$lt:小于9 [! w6 `- F7 c' ~ c
$gte:大于或等于1 _+ ^6 r9 H7 m1 o W# L- k. s. Q: Q
$lte:小于或等于4 @" Q9 X& z3 L7 l! I$ L" u
& c+ x% I; @3 {1 @+ ^$ O例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value l% z; {7 Q, D; t
- db.collection.find({ "field" : { $lt: value } } ); // less than : field < value2 Q" S2 P( t# N; c! U
- db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
L) U. z }# v! k0 b: K - db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码
# J% K( @' y, M+ [如查询j大于3,小于4: - db.things.find({j : {$lt: 3}});
; ~" T4 N! b& m% I. [0 r$ | - db.things.find({j : {$gte: 4}});
复制代码 ( r; F% f0 H$ Q$ n! Q' J5 v, i
也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码
: y6 L% Y# @- w3 n# C3 Y0 O& l
" F3 b( c, G, E
F7 J* d1 H$ e5 ?0 C7 z2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码
P I: f5 C$ ^# C4 ?+ S; v* G3) in 和 not in ($in $nin)
$ L; C( m9 y" n7 `6 P5 P+ l0 ]8 {) T
语法: - db.collection.find( { "field" : { $in : array } } );
复制代码
5 T* S: E4 j/ \0 B: b! H# K& P, [例子: - db.things.find({j:{$in: [2,4,6]}});
0 h. h; \0 X9 {0 k7 s; D - db.things.find({j:{$nin: [2,4,6]}});
复制代码 * y# q! Q2 t- u" X
+ x( d# d3 Q: U4) 取模运算$mod6 r0 F( |& R/ }7 a' m+ U
: ^0 l: B+ E9 ~) O2 V
如下面的运算:
- db.things.find( "this.a % 10 == 1")
复制代码 . ]" q5 C! d E( J1 l) }
可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
) o8 Y7 s6 K6 Q% Y7 m3 O) R. R/ R M( C6 @
5) $all
# } d' A/ l T
3 t: k/ c- ^$ _1 p1 E% M$all和$in类似,但是他需要匹配条件内所有的值:
. s& d& p7 O, M$ f: H, o4 ]4 }" p0 L B7 U* k: d8 x
如有一个对象:
% k( n: P3 o2 D# H# y# v- {: j! u
, z0 i; B4 {9 j! ^ ?" W2 x4 R3 P下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码 1 x- L$ \* F/ z, ~
但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码 2 G+ x( ]. G+ u& T' f8 F# h
% k2 |' s {$ l9 |6) $size6 o6 w- H4 a2 C
2 }8 e3 p% n7 o6 K
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
^ D/ k+ l5 F5 T* O# {8 S4 N: m1 ?4 M0 C4 C |9 W5 ~
下面的语句就可以匹配:
- db.things.find( { a : { $size: 1 } } );
复制代码
/ H T" l' T; P& z' X6 e; k官网上说不能用来匹配一个范围内的元素,如果想找$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. 4 l; z: @0 h7 u4 @: S
7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
: I8 X0 z: e ?6 g - db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码 / P$ u4 v+ k$ H! L- Z1 v: }
8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string) E0 [1 @( p' [' |. o0 }1 v
- db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码 ?/ q/ J( Q' R! E' h% M8 d
9)正则表达式 H1 ]1 @8 J) {* M; Q
3 \$ k: i/ q0 d3 a# ?mongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码 7 N7 W2 y$ x; d* K0 l+ P6 ?6 H0 R, z$ K
10) 查询数据内的值
% M4 T, s" T# X2 @- O( q, ]& `- k
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码 % J m+ ~, S3 p" ^2 U, e& z
11) $elemMatch
/ }5 b; f9 a/ y1 e0 J3 d% k* O; B4 V* f5 U6 Q# Z. J' r
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
8 r0 w7 R2 M7 e - { "_id" : ObjectId("4b5783300334000000000aa9"),
- k2 D* ]; p) H% g! c - "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
0 ^% }/ @7 v9 `( p5 L9 i4 ?. V - }
复制代码
' M' ]- b1 Q% L+ u* G$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
. r3 L+ I2 Z! B2 B! p, ^5 T& i$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } 1 y' [5 T" m: x+ ^( b
) Z9 {0 p& Z* X8 }. Q
12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码 1 c. K! ]. S; E- w% f, b
举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码 ^, X3 @0 j$ k" w: e: `& p( {
如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码
) \) |- A$ C3 b, Q t: F4 V4 K& ~5 Y如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
7 i9 r& a4 A4 x" G4 A% T' r下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
m% R4 U4 p+ s是不能匹配的,因为mongodb对于子对象,他是精确匹配。 , c, Y& A, f) | [% K9 A% x
13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );
$ U4 f$ g" l. K4 c* U( k) i% U$ g - db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码 . |% u* W( l% [8 s4 V5 r3 G
shell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin 5 G! U& O+ y" \: T( l9 P
7 l* W+ j$ [! G6 |
2. #增加或修改用户密码 3. #查看用户列表
0 J6 r7 J: g' J- [! r3 Q: v 4. #用户认证 5 l2 A2 ^$ M1 _: n0 @, A) B8 _
5. #删除用户 6. #查看所有用户 ; ]5 k2 H, Z) g! `( N- h' u& ^! V. u
7. #查看所有数据库 8. #查看所有的collection 9. #查看各collection的状态 - db.printCollectionStats()
复制代码 / V5 ]$ @( q5 O' M; k4 ?
10. #查看主从复制状态 - db.printReplicationInfo()
复制代码 % Z! T& W8 {+ H1 S' G# r
11. #修复数据库 12. #设置记录profiling,0=off 1=slow 2=all 13. #查看profiling # }9 v3 n/ k' }, G! |% i2 q
14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码 - a! N% r8 k3 ?$ H* t
15. #删除collection 16. #删除当前的数据库 # D. K5 N6 C; l. t- G( g& c7 b+ L/ c
2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码 7 o0 f* J' Z5 q, a
2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码 5 T# D$ R$ m7 y* a6 V- A( B
3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码 " S W! d% B# s. c7 G/ L
4. #删除yy=5的记录
6 n$ h6 n. e, N" r/ M4 i& Y/ u9 } 5. #删除所有的记录
6 V+ N1 c: m; [: s# Q+ h; Q6 t 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()
- H9 y$ L7 x/ | Y! y9 t# v& q3 z2 W: i6. 高级查询 条件操作符
/ @ b- f! j( j& x9 I- $gt : >
9 }; g3 X1 d5 d7 k - $lt : < / x5 u6 L9 [* L7 E
- $gte: >= $ M$ N8 P$ d6 M7 l' V
- $lte: <=
5 {) ~) U r7 L/ O3 q* d2 \ - $ne : !=、<>
2 Q; B( w x. c& ]; i. b3 o0 y* } - $in : in ) `& Q- D% R* [6 P- D$ H' s
- $nin: not in
, W. g9 s/ F; Q. F* ] - $all: all \% F# w& v S% X6 ~4 X
- $not: 反匹配(1.3.3及以上版本)
复制代码
& i3 {5 h1 {2 O: v9 y" l0 h% F
L- r+ g- A; t1 x1 w8 ^, ]查询 name <> "bruce" and age >= 18 的数据
" ~8 A0 l/ C5 M& y, f/ D* [- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
% _/ a6 A* m( j+ U! G O
' a* T/ w# c1 R" {8 b6 w, Q查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 . g7 r# x/ G( k8 H+ ]) ]
- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
3 I4 [6 s' b% ?9 g. u' o
: i- C7 w( M3 ], B) e" W1 t$ v! M. s查询 age in (20,22,24,26) 的数据
z" X# ?. F+ Q# N, @! c( ]# r- db.users.find({age: {$in: [20,22,24,26]}});
复制代码 ; n" a- {: k" j# n( w& i2 a2 }: C
a. @/ U$ ^/ f+ w) b0 O+ _( P查询 age取模10等于0 的数据 6 f8 U+ {8 q5 n2 Q6 b
- db.users.find('this.age % 10 == 0');
复制代码 6 E# Y4 E* y& Q6 v; y
或者
" Z! n8 I; m% ]- }! r% L- db.users.find({age : {$mod : [10, 0]}});
复制代码
- n: p0 t& A/ `( O- G7 Z6 p# h. `$ V2 z9 }9 t, O2 o- h- T, i$ {: |
匹配所有 3 h- H7 t0 _9 i8 m5 [" f5 n
- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
1 ^1 Q, E9 |6 p) |9 B# G {1 P可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } ; W0 d- H. n0 g$ p9 D8 F" O# {
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
; Q+ x5 W1 ^0 i7 l% g# T: R
9 P% z: @ ^9 k, O1 o) G7 N查询不匹配name=B*带头的记录
7 t! S4 [. ]% R- db.users.find({name: {$not: /^B.*/}});
复制代码 7 ^9 J2 P7 `- ~1 ~; C6 n( ^
查询 age取模10不等于0 的数据 : u9 l, p, e3 w/ q
- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码 ' Y" L: I$ I& E! N: B4 W) X0 u
Y( G0 K; O! n1 g( V#返回部分字段
5 }4 d$ M% O& c* i7 G$ r选择返回age和_id字段(_id字段总是会被返回) 9 X* ~- J) P7 F4 D# v r2 B
- db.users.find({}, {age:1}); b* e) Q+ E% g' o* r4 f. T! d/ M
- db.users.find({}, {age:3}); " ^8 k$ R- @; d# Y
- db.users.find({}, {age:true}); 6 \/ o# w4 W0 x, M* ?1 E
- db.users.find({ name : "bruce" }, {age:1});
复制代码 ! `2 x0 ] ~( u$ w; R9 t
0为false, 非0为true
$ b' d3 g' A( E2 Z0 n# X; @" S3 z0 D$ I# R$ S( K2 I5 f0 H
选择返回age、address和_id字段
" W! q& u3 C9 ^1 c, f; y; N0 f7 G" @- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
$ T0 ?* Y$ s0 b: [7 o( H+ G& U/ G$ B1 W
排除返回age、address和_id字段
3 r& q% y- m7 P- db.users.find({}, {age:0, address:false}); 3 P: t* h, R d% g n
- db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
5 n J; q5 R0 x( a
+ H9 J" a4 ^" l9 T6 R数组元素个数判断 9 k9 H5 v4 r, Q
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
6 M; N% I' p3 t" w% L$ l! P匹配db.users.find({favorite_number: {$size: 3}});
! b) g) a) z: }+ ~; a9 t, x不匹配db.users.find({favorite_number: {$size: 2}}); 4 Z( g7 L! K& ]8 w- r
$ V2 B7 q, c. w$ a7 H; c( z
$exists判断字段是否存在
) _ D2 P; z( E7 z% j查询所有存在name字段的记录 5 f. j% Q) U2 l4 P# b$ h
- db.users.find({name: {$exists: true}});
复制代码
q" L2 C5 V+ f7 m7 x/ I; \查询所有不存在phone字段的记录 & z! t2 ], H( i( m4 D# g0 q
- db.users.find({phone: {$exists: false}});
复制代码
; `* a, q: O. U8 C K# e& b+ N0 j0 g5 a
$type判断字段类型 4 N ~+ O0 y6 ]% J/ i% u
查询所有name字段是字符类型的 6 X: D0 `6 d0 _( g! {
- db.users.find({name: {$type: 2}}); 1 a2 ~7 c/ V0 c* A' r+ D$ u
复制代码
, x$ D3 G" d1 i( h# S) F查询所有age字段是整型的 8 M& @$ W! d4 t7 r( c
- db.users.find({age: {$type: 16}}); b. B$ L. ^: ?: A% @* Q4 W: o% _; D7 v
复制代码 # |2 c4 x8 `) C- ]
对于字符字段,可以使用正则表达式
( G. Y7 q6 H4 @" a# ?7 _" V查询以字母b或者B带头的所有记录
& Q# d: W/ U5 ?; Y1 K2 w; H- db.users.find({name: /^b.*/i});
$ a9 G; z I2 U D1 _& z! T4 R
复制代码
# M8 ?# l# J1 {( {: y8 C: d5 b$elemMatch(1.3.1及以上版本) 6 B( k: o; l# z- M
为数组的字段中匹配其中某个元素 / Y( ~0 t9 k \. D; z; s
* @& c3 C2 s0 `" P5 OJavascript查询和$where查询 ) S* D) q) X# R$ ]+ w# e4 W4 {) H
查询 age > 18 的记录,以下查询都一样
! y# q5 Y( l% o5 v- db.users.find({age: {$gt: 18}});
" Y/ ^: ~6 W& A2 A1 A2 I - db.users.find({$where: "this.age > 18"});
2 k/ p: ?. A# }% K - db.users.find("this.age > 18"); % h! `- p$ X/ ]* T' v! V1 H$ r8 |
- f = function() {return this.age > 18} db.users.find(f);
复制代码
& o& `7 s8 b, y+ m9 t/ S1 ~" u6 F- v! I) U5 j+ X) O
排序sort()
! n( n1 p- N1 X) r: W以年龄升序asc * p j7 w' n2 E5 k" d
- db.users.find().sort({age: 1});
) ] \' E/ O5 W& p7 A: R
复制代码
3 i! l. ]6 T9 k+ `2 b以年龄降序desc ' [8 Q2 e7 W' o5 @9 `/ K2 Z& t4 @
- db.users.find().sort({age: -1}); 4 ?" O( o% Y3 m* _( @. R, h; @
复制代码 % |! V' g( J% _3 C, ^) o& ~
限制返回记录数量limit()
# v+ X# b k6 F返回5条记录 $ q0 c5 Z2 g$ S
- db.users.find().limit(5); ) P; e* }+ D7 z/ ]# a z
复制代码
1 Q% w! K- m5 X8 m返回3条记录并打印信息 - O) |; J. z+ {5 T# ^" C
- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)}); " ?1 N5 e8 F7 n* l) a
复制代码 " \, c' C4 |4 P) `1 Q: J
结果
" c2 r/ V2 m) b/ n S: h- my age is 18 6 o& E5 G. M$ `
- my age is 19
2 {" [3 x; W, U. _/ ` - my age is 20
复制代码
' k2 k8 y5 X% c' o, d3 V: X" C8 O& |3 @+ @
限制返回记录的开始点skip()
+ {7 ?( p2 u3 ?- _从第3条记录开始,返回5条记录(limit 3, 5)
$ S% j/ ^2 `, | W4 _& s- db.users.find().skip(3).limit(5);
( z/ _" d0 X" }/ F! c" J3 K
复制代码
+ {) s" {2 J8 }2 j% a, P g7 t% B0 D查询记录条数count() $ q- i% Y8 Y$ Y+ `1 j, q0 @3 d
db.users.find().count();
. K+ [7 X) R; c2 J$ Sdb.users.find({age:18}).count();
5 h; k: Q& C9 A0 a. t3 a以下返回的不是5,而是user表中所有的记录数量 6 G8 u2 s' j d6 g8 {3 U1 G
db.users.find().skip(10).limit(5).count(); / c0 B. V ] a
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
$ s" l2 C/ z: Z' l% t- db.users.find().skip(10).limit(5).count(true);
复制代码 & K3 y% l3 X M }8 A
* U1 k6 o4 U$ V7 q分组group() 2 p8 ?7 `4 c6 s" D
假设test表只有以下一条数据 ; Q& t" Q$ @9 z! t8 y
- { domain: "www.mongodb.org" 5 T7 _0 Y2 a% R' D$ X0 i3 T
- , invoked_at: {d:"2009-11-03", t:"17:14:05"} ! a' t5 k/ a* Q/ T: n/ `
- , response_time: 0.05 , u- Q3 v8 T+ m" Y+ l5 J6 F; [+ m
- , http_action: "GET /display/DOCS/Aggregation"
& S' y( G: X g9 w5 g5 e - }
复制代码 # G* O( T8 }7 _5 K* t7 E. t
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; 4 p5 u4 e# P4 k V$ c
- db.test.group( * |1 O" [* ?+ J, o! m
- { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} * G# a# W$ o' m9 f
- , key: {http_action: true}
8 C% \, H3 o; g6 o - , initial: {count: 0, total_time:0} 6 M7 M3 g ~# e0 g4 |1 ^) ~( z' N
- , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } ! f$ f! E! r8 [) ?
- , finalize: function(out){ out.avg_time = out.total_time / out.count } 7 T/ K! U5 o" |4 W- o: W$ Z5 u8 J
- } );
; j) L' E& E+ a+ ~
$ t. k* S& ^/ q0 q% S- [
0 a3 T4 `3 p/ A- ?1 K - { " P8 J: ~) g! N1 \
- "http_action" : "GET /display/DOCS/Aggregation",
4 _( V/ R1 j+ C- ^* R( h) |2 f' F4 U - "count" : 1,
/ B7 K1 t9 l1 l7 I& Z/ G - "total_time" : 0.05, & ^7 e6 p7 \" V x. n
- "avg_time" : 0.05
% V; C. t+ `( C! ]1 R - }
. _7 ]% a4 v! v4 B- g7 a8 \, r - ]
复制代码 7 | H, b; ?/ g& U4 z( U
2 e4 e% d8 Y" [% o" t
G3 h& C" |) I$ y3 J3 P$ \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
, n; K: @: d1 G$ _; d+ Z" b
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码 4 e: \2 V9 f: s8 V' E
+ M8 _3 j6 d5 @% A D! l2 S* [9 a) N* S( e
$ v8 e1 Z% ?) ~$ Z0 i! J
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 - distinct; d: K( q9 S- ^$ ]9 m
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
$ u" u3 b/ g4 b! `8 S
, i+ k8 n7 ?. c8 B: O 他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码 . j; G8 Z1 Z2 d" p: }( n
2 p" F x: E6 k 我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码 0 j5 C0 o# i! @& V L/ f
5 }7 o/ j7 B! Y* W" D) k5 l a
我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码 ! u+ ^6 v0 m* j
" K: J( j& f! p3 y; ^ R
输出如: - " I- Q$ Z3 i& C+ i: t
- [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码 9 I6 W$ {* }8 o( S4 J- S# T
$ i4 Y0 _" O" @' S/ x. A) g# P5 x' I# }! X1 z
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"" G2 b( p* ]1 n T" I3 D
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
9 ~9 I# K0 W U! h4 }9 M5 R - xmlns:context="http://www.springframework.org/schema/context"
6 s3 y2 r, N' F, y - xmlns:mongo="http://www.springframework.org/schema/data/mongo"4 ^8 V$ k8 y i9 K6 ^/ h3 V, E" j
- xsi:schemaLocation="http://www.springframework.org/schema/beans# m6 O: |7 L2 u& N
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
" s: d. v$ G/ Q7 R# t( M! ^4 Q - http://www.springframework.org/schema/context
$ L2 {: W0 w) A `8 I- b( C. C9 H/ c - http://www.springframework.org/schema/context/spring-context-3.1.xsd" }: n z2 [- Q" j" D
- http://www.springframework.org/schema/data/mongo
6 i# O3 @! b$ b - http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">7 z" g7 R) H+ m, [1 O
- % e: b, c" ]. {: _/ ?
- <context:property-placeholder location="classpath:mongo.properties" />
3 D- h4 A1 p7 k- b& f! v - ) d* r: ^7 {3 f0 t% ?
- <!-- Default bean name is 'mongo' -->4 k- Q. ~+ S6 S2 S
- <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />$ s8 D! N0 j/ b1 T" x7 W) H# `! e- T9 R
-
& H; {5 O$ ^/ b6 _# W) w" n - <mongo:db-factory id="mongoDbFactory"9 ~2 V$ R3 x1 R/ d5 e8 U. A9 k
- mongo-ref="mongo"8 j; Q& x; b, r( z% [
- dbname="mongotest" />
2 E1 G8 J, t' m; ?! r -
: h9 V. ]% ]4 t7 n \ - <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">9 j# R8 j4 b+ U. p) z+ P7 N: _7 k
- <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>/ i/ i! c; e2 A' Y
- </bean>( X9 w6 r6 F: O
- </beans>
复制代码 - {) W4 X# I' {
$ L4 y4 a. h8 w' |0 m3 {2 g8 E max和min的测试: - @Test
, I, M L7 u* z- d3 ?. J6 i* J1 J - public void testMaxAndMinAge() throws Exception {9 k, U" Y4 f' G1 U: j7 V- P1 Z
- Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);% [ t) c: y/ N& i( E' M% s) P
- Person result = mongoTemplate.findOne(q, Person.class);
4 b8 p) h- Q2 O/ m2 _# y - log.info(result);. ?" @3 Z" F) V! @2 P$ u
-
/ F& {: h2 g; D# Y$ Q - q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);0 z3 Y: A; C- W: f" n, f# @
- result = mongoTemplate.findOne(q, Person.class);! `1 U) [7 j4 f3 ]# c
- log.info(result);% h* {- I f4 O) ]! j1 t9 ^5 X
- }
复制代码 5 Z0 y' b2 A- h( B- H
* z6 V! R# `+ K- l8 b: g
distinct的测试: - @Test7 J X' J4 C' z+ |) s; ]
- public void testDistinct() throws Exception {
7 G5 @9 E2 k w, T. n/ H - List result = mongoTemplate.getCollection("person").distinct("myFriends");
3 E5 I$ \$ k$ L# u/ C/ I$ \! ^/ v4 O - for (Object o : result) {1 n3 [9 _3 B* a7 A0 Q, x& W6 u
- log.info(o);
3 J1 ^" @1 Z; N& s( ^ - }
( w7 H0 z% \2 h8 X) j5 ? z/ ~2 | -
1 {' P1 v$ l" W [ - log.info("==================================================================");7 z2 ]/ Z( @& E. ~. {7 h4 E
- Query query = Query.query(Criteria.where("manId").is("123456"));
8 D* v0 _0 k! i" R - result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
. B* S8 t; o( }& x( u& C% u0 T - for (Object o : result) {
1 t7 p& E9 d% Q( ~3 o5 F - log.info(o);
& X6 C- O( c1 I- ^& t) U7 A - }# N8 r O8 i- G" h4 J3 b- d- ?
-
6 k0 R4 I0 ^6 s! c0 W7 M - log.info("==================================================================");
U9 l0 O: g+ j3 K3 ] - result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");/ t8 i* E% M* |) @1 q
- for (Object o : result) {5 ^6 W. ?1 v+ r
- log.info(o);
* [# s8 O* `/ f7 {% r z - }9 s9 D) A# Y6 {+ @0 f5 Z3 W4 b* b' f
- }
复制代码
$ U! F: T2 W' Y' v
9 Y( f% H: k& p& [2 Y$ i 输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
% T, U$ ~0 S- w& G5 ~ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
0 j# z* x6 \+ F. ` - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
+ [* `: i2 q+ ~3 V - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
) L# _( h; m( [* G$ } - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
4 v, x$ I8 q' W2 x4 _* n - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo5 \: Z% q9 \- `8 n7 m/ Q! A \
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
1 g% ~/ e! O, s" ?' N2 b - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
2 \( b6 r1 }- ^4 T) D+ ?7 Q - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
+ }$ A% k+ I, T2 h; G8 R - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
, V: ^5 T) D; }0 Y9 D9 Q) x5 N - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
4 ~( U5 j: e4 c$ z2 h) M - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876543 v) K4 I& F8 C
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================7 X8 U" ~. h" }( z3 W4 ^
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa* Y& u8 c9 K) R' V7 H
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb6 s- }" g* o' I* y) T. v+ t) l- i
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc9 _" Z8 W) H% q' p5 x
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www2 m6 l( G$ Y/ E8 U) I' F5 g" C
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
5 q5 O1 v U& i4 D& Y5 B; f6 i - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
3 b, Y# w4 @) H- z9 z/ g - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz8 E+ U+ R. E# }/ [
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr3 r: w/ I; I6 r+ B+ ^8 P
- 12-22 14:13:45 [INFO] [support.GenericApplicationContext(1020)] Closing org.springframework.context.support.GenericApplicationContext@1e0a91ff: startup date [Sat Dec 22 14:13:44 CST 2012]; root of context hierarchy
复制代码 8 z5 i3 R& p0 `+ d Y, h3 Q
1 Y1 ~+ b. A5 q$ ` 这里我要特别说明一下, 当使用了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等信息。 - V$ \5 @, Y( r
/ L6 \3 f" q- j i4 W& p9 B3 Z7 C( _5 t
|