版本一:
2 ? Y7 k( M" v. |3 Q* e$ h' }
) x+ J r8 A, y3 y" ^1 ) . 大于,小于,大于或等于,小于或等于; `6 U% U% r- ~: |
+ I3 v/ q; A* M- A1 _) @$gt:大于
4 |( t1 p2 `% L$ u2 G0 V$lt:小于, y$ t: l# A5 i8 J/ a/ C: W6 t
$gte:大于或等于
6 [3 Q& y' F0 L q0 g$lte:小于或等于
; {; g: ]2 j0 t0 u" r* l$ x7 ^
. Y: W2 M$ X1 p" S/ A; }# y例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value8 k y7 h4 m! U/ L
- db.collection.find({ "field" : { $lt: value } } ); // less than : field < value1 c9 P3 _1 b6 a+ j, S) J
- db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value r) b# p8 h; a/ B. h
- db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码 / Y& _2 k7 q$ ?5 ^
如查询j大于3,小于4: - db.things.find({j : {$lt: 3}}); Y' h/ U2 d) x0 K
- db.things.find({j : {$gte: 4}});
复制代码
' q$ v# J$ s: |0 H8 g+ N) C: Z1 F5 b# x也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码 : K7 Q7 h& L1 X$ V6 l3 p; ^& h% R
* `% n. R3 z8 E8 Q
' V4 L c0 C- w/ _2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码 . c" p r! E" b( m5 [) K6 \) [
3) in 和 not in ($in $nin)0 \9 e1 w* U8 M2 Z
, B# \+ @/ d3 i$ B5 C. N语法: - db.collection.find( { "field" : { $in : array } } );
复制代码
- y! G+ T8 m: Q/ O- h例子: - db.things.find({j:{$in: [2,4,6]}});
6 S* A' a& h* q4 ], l - db.things.find({j:{$nin: [2,4,6]}});
复制代码 2 i6 n$ u, E/ x
; O& `% U$ x" q1 M9 M6 J4) 取模运算$mod
" p1 V- ]9 K% ` c! J2 F' ^* _" V! ~, ]+ M4 O$ |/ m( R
如下面的运算:
- db.things.find( "this.a % 10 == 1")
复制代码
6 J3 Y7 M! @6 L" A可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
( a$ E9 O! \9 {6 @7 @$ q
0 X! u& p4 q8 y& p4 @! p9 _' ^5) $all0 E8 c5 [' s- b; {( H0 c M
. A i2 [, H: s5 w# F& ^; s$ j
$all和$in类似,但是他需要匹配条件内所有的值: p: K/ r% Q/ v8 f; R
0 g3 f0 Y8 w$ p! [如有一个对象:
, c B4 _8 D9 [
. a- N) r) T: b/ l下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
0 x( Y+ A* n3 [8 j0 A. e: y但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码 2 F' f. T+ f9 [. }, _3 D; I
" D2 a# P$ y; ^! x& O
6) $size
' Z- y1 f1 Q# l. a6 g. t3 [( A' d9 }- B2 v1 p& w
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
% a6 F: J- U6 [- t$ ]
: B9 e9 _7 m: x$ R+ V# [! [: k1 d下面的语句就可以匹配: - db.things.find( { a : { $size: 1 } } );
复制代码 9 z# W8 a% r& J0 V0 e( p
官网上说不能用来匹配一个范围内的元素,如果想找$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. $ X% _2 j+ S8 Q& P; z) L+ B6 H/ U
7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回* R9 G6 M4 u3 x0 g E
- db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
0 d k- q+ c' b; u! j4 e8 B8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string
- z! J0 B' T7 W0 p/ F - db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
; W8 _( y. J2 J4 K; A. B9)正则表达式 G* ]* q1 C# [* F# C: n
' \4 f% m! f s1 r# ^' H' Fmongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
& v& X# c1 j: k7 q- S10) 查询数据内的值
! D1 N0 S2 m0 r0 U) L
' y3 j. [$ P0 M; T8 i下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码 & f: t* w% b" g& ]
11) $elemMatch
2 h4 Z' P' D. C0 e
7 ? y' d) q/ [0 T' t, t" C2 r如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
( M1 P% W6 E5 \, m" i8 N* j - { "_id" : ObjectId("4b5783300334000000000aa9"),
, j( {% v4 O+ Y0 X) v( c1 j. u - "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
5 t- t& P: n1 n( O9 ^, h% B$ ` - }
复制代码 1 R7 g9 u8 C& k8 E, C6 v
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )0 I& X8 j4 c0 Q3 q5 s
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
0 v. Z% C0 e8 w( K6 w$ R3 p( a0 N7 r
, u9 K+ c6 d3 s K$ \6 u- c* Z12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码
) M8 S# b* {( J s& O5 P/ D: [举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码 % [' d7 ^/ w- E. ^+ e& g8 d9 U V" F
如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码 9 t# D: h; R0 }# S% Y( P+ R6 B5 l
如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
+ ?9 v( \9 X% G6 \* H下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码 - O/ L; ~ `9 w3 e
是不能匹配的,因为mongodb对于子对象,他是精确匹配。 0 o/ F% V. H4 `% I$ f" L8 Y' e
13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );8 v8 h f7 u q
- db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码 7 w# c2 C4 f7 M$ U
mongodb还有很多函数可以用,如排序,统计等,请参考原文。
" g% A0 R) \% A2 i' z$ [$ _) L
& }3 i: H7 K1 T% s9 ]: \mongodb目前没有或(or)操作符,只能用变通的办法代替,可以参考下面的链接: 4 r3 \: G2 J) s9 H8 t
# H: \. I& Y4 U( C8 k2 I. W7 e
http://www.mongodb.org/display/DOCS/OR+operations+in+query+expressions
. k% y! u4 ?* j7 g/ u3 }' \4 Z' t4 T% B. A- O/ L# t e$ _: K, n4 @ z# Y
版本二:
" z' e! O2 T [' Z8 X. H2 _shell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin
% I4 I z& |0 I. A E% k) D) O* x0 ~
2. #增加或修改用户密码 3. #查看用户列表 4. #用户认证 5. #删除用户 0 b1 o7 D: g5 B4 p7 b: M4 g
6. #查看所有用户 7. #查看所有数据库
) B; J; L. H: `4 M. G" N1 r% H5 ~ 8. #查看所有的collection 9. #查看各collection的状态 - db.printCollectionStats()
复制代码
4 J0 ]6 p9 ]3 `( Z. s" s! {0 V; i' e 10. #查看主从复制状态 - db.printReplicationInfo()
复制代码 2 v% K4 Z* F2 y1 c2 G% ~
11. #修复数据库 12. #设置记录profiling,0=off 1=slow 2=all
* o2 `/ P+ ? v$ Y% [2 T' `8 Z( c% y 13. #查看profiling 14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
; n7 T& Z8 o; R! D4 \1 O$ P 15. #删除collection 16. #删除当前的数据库 2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
, v9 L3 @4 e, Y- d2 u3 ?" i9 s, l$ m 2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
2 m* a" U# r9 o" u+ u$ A 3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码 : M4 O) X! [0 f5 S2 B+ V
4. #删除yy=5的记录
2 C! v) s5 q+ r) z' d$ }) F 5. #删除所有的记录 a- {; D: H$ p0 U! X! _. {9 U
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()
$ w& ^% u K" M- d# T6 T( T: I6. 高级查询 条件操作符
/ V% i- L9 o7 v/ W8 w- $gt : >
$ Z( f" j$ i4 Q1 A6 x& g8 D - $lt : <
6 Q3 V2 i( W% S4 c" Y; O1 E! Y - $gte: >=
! Z; d$ M* B0 j `; w - $lte: <=
1 W6 G$ b# r( Z8 J - $ne : !=、<>
# b" ` L8 B: E+ y - $in : in . n* ?! E" E- B+ D
- $nin: not in
4 w% w+ O9 z, e6 }! L9 T - $all: all . R- L% E/ m1 j# Q8 P/ N
- $not: 反匹配(1.3.3及以上版本)
复制代码
( [- V4 ]: a( G. L7 M! u" n8 ~6 \3 b5 y3 {
查询 name <> "bruce" and age >= 18 的数据 + k# J) G6 t( g1 B4 e
- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
) g, L5 C) b7 k0 q# w
% B9 s& v6 c3 z# Q. p% k查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
+ G1 ~. }' x! r: I2 u8 F/ C; y5 A- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
6 p: ^% g9 P! {1 N( O# f
$ q% ~" o7 c+ ]6 w {4 k( ?查询 age in (20,22,24,26) 的数据
6 i2 \$ ~ E" U0 _1 j( L' d8 q+ x- db.users.find({age: {$in: [20,22,24,26]}});
复制代码 % C- o: j+ ? f) G
' u% o( T; d5 f9 p6 b1 s查询 age取模10等于0 的数据
! `0 ]& h/ H9 O& v3 L- db.users.find('this.age % 10 == 0');
复制代码 . A2 E. t, h* E
或者
' S, A; r' A5 T$ D( m- db.users.find({age : {$mod : [10, 0]}});
复制代码 ; `7 m& H) c; z* J- d- g: Q
- A4 w9 F& w5 C& d匹配所有
# J6 d- W& Y! B3 e9 g- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
( Q) C `5 s0 u4 M* U可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } ; p- G2 N! ]2 a' u8 C0 O L! G2 \5 w
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
; m. s D0 ]3 G5 V$ b
$ a0 V5 D3 T$ C- Q% s: }/ p( r查询不匹配name=B*带头的记录 # _; y, t3 [, T& ~1 @( ^( ^
- db.users.find({name: {$not: /^B.*/}});
复制代码 + b" C% t2 x' T
查询 age取模10不等于0 的数据
+ p. u' \1 a/ f7 L- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码 % y K, d2 j. x" }% }/ s }
4 l- O8 j7 B! y2 I+ p3 f( v#返回部分字段
& {5 U& r8 L) T选择返回age和_id字段(_id字段总是会被返回) + V' z) t5 }) I4 A# f
- db.users.find({}, {age:1});
3 c: {7 }- p! l5 [. q - db.users.find({}, {age:3}); 1 q3 b9 }' Y0 D0 [1 e0 F2 {
- db.users.find({}, {age:true});
" `/ e8 o* G5 |7 ~4 @$ Y - db.users.find({ name : "bruce" }, {age:1});
复制代码 F: l1 \3 e1 h
0为false, 非0为true
$ ]7 i2 H/ v {5 k( g
/ r2 _! b% V2 h2 ~. Q# i0 \) a选择返回age、address和_id字段
s9 F7 b; V9 ~# Z! a+ m- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
2 s! [+ U. x2 K; j& H
2 E" y3 y Y( l S1 s* d排除返回age、address和_id字段 % U+ `* h, A2 N6 P) W
- db.users.find({}, {age:0, address:false});
. w8 p2 s! p1 h! w9 r# f3 d% v - db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码 2 v6 e0 s; l, F) E" a
9 ~& A" d2 M& }5 @. u
数组元素个数判断 ) H1 E5 x" `/ E. E
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 . a. S. v$ U" u; m& s
匹配db.users.find({favorite_number: {$size: 3}});
2 g, S& `% t/ V5 h7 e不匹配db.users.find({favorite_number: {$size: 2}});
4 |" w" c. k( i: h. k9 l4 `1 x. F2 k3 P9 r5 y
$exists判断字段是否存在
9 {/ S% p: A2 b. O Y, I( q查询所有存在name字段的记录 0 c) t }3 y6 I b6 J7 L8 L
- db.users.find({name: {$exists: true}});
复制代码 " z% c2 Q" Q3 |* _5 M. q+ d; S8 y
查询所有不存在phone字段的记录
) ?1 t( A% Q; i: T0 L3 X- db.users.find({phone: {$exists: false}});
复制代码 7 u6 n, N; E- _' C* p
* \3 O" ^ @1 Q$ f$type判断字段类型 # }; _) g" E' G: ^8 O
查询所有name字段是字符类型的
- o# F0 L0 K0 i0 R! l% K- db.users.find({name: {$type: 2}}); : F: f# C+ p) |4 {5 r" {
复制代码 ( H/ ^8 Q+ t: x7 T9 }$ b& \4 `
查询所有age字段是整型的 3 o; T2 F# X1 w& }5 ^
- db.users.find({age: {$type: 16}});
& }6 w( E2 c# r& f) f, n) B: d; h
复制代码 % R3 }" h! x- J" K1 H; |0 W
对于字符字段,可以使用正则表达式
$ b7 M$ O' {! u% N1 E9 A查询以字母b或者B带头的所有记录 ( q% l5 K! ^0 a5 s6 b
- db.users.find({name: /^b.*/i});
' [/ f0 `2 @# m) j
复制代码 3 W7 a5 N1 B/ B/ b4 D1 T
$elemMatch(1.3.1及以上版本)
7 i1 {* y& |! \为数组的字段中匹配其中某个元素 + R/ G* _8 {, `& F8 H
- h0 ~/ v1 t- \. q7 t% R. iJavascript查询和$where查询 5 |1 O0 l# Y& @+ H q L
查询 age > 18 的记录,以下查询都一样
) O6 `; d, _& J1 K/ y6 K6 d- db.users.find({age: {$gt: 18}}); ' O3 S/ g3 N6 {1 l1 ]
- db.users.find({$where: "this.age > 18"});
* N0 @' g& `: p( g8 I - db.users.find("this.age > 18"); + Z0 v$ V* G3 U* H
- f = function() {return this.age > 18} db.users.find(f);
复制代码
2 k* N) Q8 \% X4 v- {, d+ w& c- g. h) a+ j% j6 ?
排序sort() % m6 J& _9 ?$ f
以年龄升序asc ! J% A2 T# @" Q v2 G& I
- db.users.find().sort({age: 1}); 7 _7 s! L+ \! p g4 P. ?" o, g
复制代码
0 i4 e* U* X0 i+ M4 i以年龄降序desc 9 n7 v e; ^* p' b' Y; x
- db.users.find().sort({age: -1}); ; n- N& L! h+ q0 ^ g* W( n U
复制代码
3 E& V+ m. K' P" O限制返回记录数量limit() & n4 X4 R$ t- z- ?8 [* f: d% P
返回5条记录
7 U, @" J* [. L6 [- db.users.find().limit(5);
' T" t, |: E! e# ]- d5 S* r; V
复制代码
1 X+ U# Y: {2 e返回3条记录并打印信息
2 J" \7 w/ c, a9 s' H8 K- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
' c" i5 I" g o+ k5 G+ |1 P
复制代码
3 o6 w3 X7 M9 t( a7 f: V9 u结果
5 m- U; P( T; `0 r. z- my age is 18 ( [# r# Y) E8 M# e# S
- my age is 19 & G$ K+ w5 r4 K U
- my age is 20
复制代码 : X) r N F5 O) f4 a5 s: U
( y$ P! |! X K7 e
限制返回记录的开始点skip()
1 K+ p, J k" t" |从第3条记录开始,返回5条记录(limit 3, 5) / w/ `) s7 y8 b' _5 O: v p
- db.users.find().skip(3).limit(5);
! L/ O7 y9 ~4 s
复制代码 / Z" f0 u- M! }) J% J- q
查询记录条数count()
0 A: d6 v5 }/ t; n( W3 mdb.users.find().count();
2 L# J- p5 d9 g5 d7 G9 _db.users.find({age:18}).count(); , a; R- t2 [( b0 C
以下返回的不是5,而是user表中所有的记录数量
0 l; t8 R; Z' odb.users.find().skip(10).limit(5).count(); - J/ W7 G ~# Y8 G
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
- J* i# b0 T" {0 @- db.users.find().skip(10).limit(5).count(true);
复制代码
1 B1 U! g+ q' A2 h. p l z# j" @
分组group() 8 f! _. m5 ?0 J
假设test表只有以下一条数据
+ I, m" R L* @: T$ n$ W- [! V6 a- { domain: "www.mongodb.org" 8 }2 |. z5 h8 q0 p+ A8 [0 }9 ]
- , invoked_at: {d:"2009-11-03", t:"17:14:05"} ) s, i" p/ K9 @9 ?5 _3 D$ r7 j
- , response_time: 0.05
$ P' j4 g# Q; T - , http_action: "GET /display/DOCS/Aggregation" 2 R, D9 R% y9 h4 l7 E
- }
复制代码 1 x9 K) d |5 w5 u' a. A T" B* c
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
( p2 j% K: ]8 P) t, |- db.test.group( 8 d5 m7 F8 z3 h& ^
- { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
8 `$ U. D) W" l+ ^( L* w1 O - , key: {http_action: true} 8 a- p( ?! G% Q. c3 P, q
- , initial: {count: 0, total_time:0}
/ a' B( L% a( o+ ^* \# m - , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 2 r8 H$ T% }8 Q% m+ ~; H- ^3 ^
- , finalize: function(out){ out.avg_time = out.total_time / out.count } ; _( v% W6 T3 F2 l5 J) H
- } );
5 \ h: H) r- G: _ E! g, t - $ T- K. w# m( A# ^% ^# x5 t; N
- [ * j3 c5 V; @& O% v
- { 2 ^) ]* |/ e4 B; ?* X
- "http_action" : "GET /display/DOCS/Aggregation",
& ^" q2 m" o' u9 d - "count" : 1, & N' ^) a8 w' N. F# G& k0 E# G
- "total_time" : 0.05, + A3 t$ A% S/ G
- "avg_time" : 0.05 : q& m/ l" R1 A& M* A
- }
, P9 T& }* q9 I% B$ | - ]
复制代码 # ?) i8 q' o) B. {( }' ?# c
) i. N) S D5 L( u! D: t
. D% u+ I- i6 rMongoDB 高级聚合查询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 和Min8 \2 x, d3 L2 S/ L: T$ i
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
4 B [$ h0 P! F. i& t; X0 p
( Z3 S1 }$ U) ?+ u* A6 ?" e' e' A! R9 ]! R, w: X3 b
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 - distinct
" k; C! n O9 f2 Z9 d+ A
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码 b7 E4 C8 a; }7 w* x" |8 X# h
: g: X$ u9 d7 X( _
他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
" C+ T+ l# K& i3 ]
5 n# ^* E2 r0 o q: V t4 S+ G+ U1 w 我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码 % {: `/ m5 w# u# s6 [
( C6 f5 D5 U) G 我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码
- d* m& B/ ?3 [! f2 \0 n* V
' y8 c& W1 i4 V$ q* u2 q6 V 输出如: -
h E- P- w6 c9 F3 H @ - [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码 3 V5 K0 ~3 I# f# d
) K4 S" V7 N: N9 d. I( K. W4 ]
9 G& u1 s9 W- r; {7 I' Q5 e那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"
/ k: o4 V% T7 E& q - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
* ~4 K4 X0 R6 x8 w - xmlns:context="http://www.springframework.org/schema/context"' d* Y7 K! W5 E$ B
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"
0 x; i7 L* W& N3 e5 m+ P% ~5 J - xsi:schemaLocation="http://www.springframework.org/schema/beans
& h1 A/ q' Z: z- M4 A - http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
) |; a; p* f+ P - http://www.springframework.org/schema/context: U P7 P* a* }4 ]8 P5 t$ Y6 ~
- http://www.springframework.org/schema/context/spring-context-3.1.xsd. }4 B' F0 J3 \2 c
- http://www.springframework.org/schema/data/mongo
% m& }% e6 C% f$ _# H' L - http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
/ s# ?) o, y4 i h( m4 @2 d -
) m$ j3 h9 I: Q5 ^2 W - <context:property-placeholder location="classpath:mongo.properties" /> Z2 D9 l/ [% `3 i: W' X/ y! ~
-
A3 F* \8 ? p' v' j- f - <!-- Default bean name is 'mongo' -->
2 I2 o+ I0 S$ Q7 k- e* I( E/ a - <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
1 G3 o, R6 K# c0 y* h, N5 G - ( f2 V7 |) W( c/ X0 Z% B
- <mongo:db-factory id="mongoDbFactory"
! d! }' e( f$ J0 G+ _* Z) _' D5 ^ - mongo-ref="mongo"6 v }2 a& t5 t8 C. ]5 M4 n
- dbname="mongotest" />
4 ^8 _8 K+ o# l+ L% J2 Q1 B3 x! D2 d -
8 @* ?) G I) l. t4 h% W - <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
5 A- H# A5 J" g7 q, u, R - <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
" M/ q& ]4 l# P/ U a, A - </bean>% ]1 V0 C/ e0 f
- </beans>
复制代码
( E& M# a: t$ p6 `1 [; ?6 ? " [5 h+ h/ _0 ?3 y+ a4 p
max和min的测试: - @Test
. I+ c* s$ W0 O: N; X) m, T - public void testMaxAndMinAge() throws Exception {
' K" Y0 w* s' j' E( l% D) t Q - Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);5 h0 X4 _* ]# B" E; _4 i
- Person result = mongoTemplate.findOne(q, Person.class);2 f% \# B( O5 @! d% G
- log.info(result);0 ~' N! U8 ~/ v+ Z: F* s
- 1 {+ V B, d w; p8 Z% Q( ^" V
- q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);7 b3 R% i$ k& L* W- Z# T
- result = mongoTemplate.findOne(q, Person.class);
1 g6 V; x" D9 C - log.info(result);
& Q5 _* m6 D( y! F( T* z# u - }
复制代码 ! n) B1 |5 {0 _1 E5 ]8 `6 }
! P k5 O* u- w% O2 Y& T' e5 n; b$ E8 d
distinct的测试: - @Test! Z G; f: _5 B6 S- M
- public void testDistinct() throws Exception {. E' e3 j6 n) ~4 {$ J. ]! g
- List result = mongoTemplate.getCollection("person").distinct("myFriends");5 a7 n% k0 h# `" ?$ v) C
- for (Object o : result) {: E/ h& `8 g8 e. \; g" n; s, {
- log.info(o);5 ?( l b" V1 Q2 u, ]9 M9 P X3 ^
- }/ p2 Z% R$ b H: S/ B
- 8 j9 s; I7 m% ~" A6 u
- log.info("==================================================================");
+ i! e. R& o, l/ E* _; E7 @ - Query query = Query.query(Criteria.where("manId").is("123456"));
. x5 Y2 c( l0 K4 a4 h - result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());! R% c6 I) R. m2 T. q% W
- for (Object o : result) {8 }9 D( l$ h' W' t. X0 {4 Q% Z/ g' D
- log.info(o);4 O0 k/ i5 M6 k$ \0 ?
- }
$ Z8 R3 z, v2 M+ M+ {+ N -
) K/ ?( I7 l8 D& X' E - log.info("==================================================================");/ F6 E2 y( f p/ ^4 ^; y
- result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");* n! g1 _* p1 Q# I. ]) m, S
- for (Object o : result) {
# z7 ~& N6 B5 ?0 U! }' ~% h* I - log.info(o);
' P) L. a4 S, u2 l M - }' g% Y1 U/ f' q f: h7 v
- }
复制代码 6 W; V* M: ~* r
! y2 t( @4 x; g0 J. u 输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567$ m$ H& ^0 X2 [0 {% y
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
" Q9 ~4 \' D1 J( G0 a0 R - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 4567898 E U& l0 I! N t2 [
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
/ O# R7 Y5 B) Y* [ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
' K8 k, n1 c2 t4 _ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo; K2 f1 l' d o7 U1 E
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456/ i) Q3 S0 B# N
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================
4 U) O8 }' }4 W - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
* f! r' x# C \$ k: {8 D# D - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
8 W: S+ x) Q* R4 j1 N# Q+ V. L0 x - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
, w+ v& f8 y3 o; x1 Q3 d8 u - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876542 R) m0 n7 O% t* c# g8 f
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
' O. J3 X C6 r/ S) g' s! x - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
, c' p. d2 U) I/ @- l - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb/ p( [+ l4 t* i
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
. |# D+ o" E c% T1 k - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
: J9 ^8 s' I5 ~3 v9 V! }# A - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx" b O, N, N4 K% I/ L
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
) C3 V, y" n' j" Y- l - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
! M$ L. R, m" d' k$ L - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr0 [9 ]: @: _- Z" o$ }
- 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
复制代码 3 A3 K* W1 ^3 N2 Y% I! Q
" c( Q1 n* J4 T& | 这里我要特别说明一下, 当使用了Spring Data Mongo,如上面的findOne(query, Person.class)它就会把查询的结果集转换成Person类的对象。Spring Data Mongo的很多API中都这样,让传入了一个Bean的class对象。因为distinct的测试是输出list<String>的,我 使用的mongo-java-driver的api。他们都很简单,唯一的是Query这个Spring提供的对象,希望读者注意,他几乎封装了所有条件 查询,sort,limit等信息。 # _4 D) V! B: D1 `
. o" Z3 D, A! Y: b
7 E `! F- `) k, | |