|
版本一:, |# x- M) l# [! N( o( G5 }- Q4 O
: l2 ^9 W! W+ F+ T- O1 C4 v" B1 ) . 大于,小于,大于或等于,小于或等于
; R" @: h9 w- M3 D/ |; W/ M( @
4 P6 D# ^7 Z8 f. ?$gt:大于
" p7 { d/ Q1 }' v$ D9 P$lt:小于1 W* |1 C4 R' u) z- W6 o
$gte:大于或等于* T0 i; K- i. m8 l
$lte:小于或等于7 Y/ n" ^* i+ @9 f9 U$ t! i
3 d9 ^9 t+ s) T" o! z1 X, l
例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
, J, ` N5 |, G w# m, b+ y - db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
0 x- d0 }: J" ? - db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value6 `$ O% w( P6 ~* Y, j
- db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码
: h: r% ~% [9 z: I( j# A% }: o如查询j大于3,小于4: - db.things.find({j : {$lt: 3}});: W( n5 G0 x1 y Y% ^0 w! }
- db.things.find({j : {$gte: 4}});
复制代码
$ k; \& g# y5 J$ s) d- E* l% C8 ^也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码 : K4 B2 M. P4 I/ O, W: P( n
5 V2 i5 V! B$ n' f7 c7 d
1 a( b8 W- L) j3 J( f/ f2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码 / a9 K6 V% V! F' o) k, d
3) in 和 not in ($in $nin) |7 e3 t i, P5 R$ N2 z
. g; y# k( k( a' M; N k+ C$ L语法: - db.collection.find( { "field" : { $in : array } } );
复制代码 . x1 p9 d( X/ o- A Y; I
例子: - db.things.find({j:{$in: [2,4,6]}});
3 C# M5 F* I4 g5 ` - db.things.find({j:{$nin: [2,4,6]}});
复制代码
2 v8 `/ a* A0 N5 f! [% A& B: M* X! ]
4) 取模运算$mod b& i+ i0 ]# t7 P9 S H* G
# o+ q2 d0 S+ u+ S7 v1 X4 X- ]如下面的运算: - db.things.find( "this.a % 10 == 1")
复制代码
! ]! X! L2 Y' k6 n3 ]可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
" I6 Q# F- y; K5 O8 m' d5 s% v- y: w8 J1 h- ^3 W% Q$ U4 J
5) $all/ \. J$ m* G+ ? d* C
|8 L7 B% D g' O+ R
$all和$in类似,但是他需要匹配条件内所有的值:/ u5 {9 M1 T# F& @
! N5 b7 |: N2 @- G如有一个对象:
. C) b6 X5 e( W4 D- w
/ B. Q5 G v) J. r1 O- y. E下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码 : w4 h& [* y6 L+ x3 Y+ B7 s
但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码 0 m% k- L0 H2 i7 f+ R
" g9 \' H- T' A/ |' p6 i
6) $size" `% x7 G, c' X( |5 R+ l
8 W3 X$ }( p1 o% y" Y+ {) S0 A
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:8 L: \+ O G/ m* C- z
3 Z0 ~! n0 F5 ]* H2 b下面的语句就可以匹配: - db.things.find( { a : { $size: 1 } } );
复制代码
- I( k1 M# {7 S6 @7 G官网上说不能用来匹配一个范围内的元素,如果想找$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. " e( U5 f4 a- @ p
7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回 I( l I4 H+ V
- db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码 - {, M9 m( }* u6 e4 T8 w6 {$ d
8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string
9 q2 ^; L, C e" X" N' [ - db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
& Q: N2 G6 k1 m8 u9)正则表达式+ Z, i, r L1 o$ a) m3 Q$ q. Q
+ O1 T2 l0 Y$ E$ ?) ?
mongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码 * [+ K3 |# P- |. l# {1 r
10) 查询数据内的值 G4 \# } V* A* @: s
& r6 ^0 }5 M9 l; O8 O' y, ~下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码
1 ` ]3 x' `( L% n5 e& p11) $elemMatch
5 m- ]3 G0 R6 n* w' w1 _5 H) n9 k% y9 x
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
4 S E4 p: r' e2 i( z - { "_id" : ObjectId("4b5783300334000000000aa9"),
- x4 T$ N8 O2 J4 q# C$ _ - "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
" m. [2 F" W) i" H) l: z - }
复制代码 8 ~. G6 d$ W) e* V+ G
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )- Z" l" d* z+ q& N% i6 Y5 h" G) u
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } : k1 S( d* q7 N. x' m0 Y
( {' _+ r$ s8 f; ~% ^2 X
12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码 0 q+ N6 I/ V1 q" v
举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码 # p8 F. r0 j% n0 l
如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码 0 J1 _! O9 f/ n% Y Q
如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码 0 N ^9 h& y, l1 b6 `, v
下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码 p7 C# N# v n1 G) G) b& ^, Q
是不能匹配的,因为mongodb对于子对象,他是精确匹配。 4 Y4 k/ e* z: t3 |
13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );- N+ L: e" @% ~6 O" }9 s# H' y
- db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
' d4 Y1 a# Y. Tshell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin 9 ?/ U. x8 F( }2 y4 _9 O; R, T
. K, g# k$ K a/ X. k 2. #增加或修改用户密码 3. #查看用户列表
( q, ?9 |$ i) E4 e0 U6 J: a. [" X 4. #用户认证 5. #删除用户 6. #查看所有用户 7. #查看所有数据库 8. #查看所有的collection 9. #查看各collection的状态 - db.printCollectionStats()
复制代码 & p4 _( `6 ?* D% c
10. #查看主从复制状态 - db.printReplicationInfo()
复制代码 ! ]1 a9 C6 a& a& T: l! J! H
11. #修复数据库 12. #设置记录profiling,0=off 1=slow 2=all , y- c7 [0 ^2 o. F' S) {9 Y1 x2 f" f
13. #查看profiling 14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码 2 O! j5 l: l/ S/ b+ ~+ S: L# V
15. #删除collection 16. #删除当前的数据库 2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
4 ]' S0 \4 g: S/ H/ n 2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
' J- R5 z8 j3 q$ Q% H5 t. A$ P/ E! O 3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
5 t# m5 ^- I& z4 B6 v _ 4. #删除yy=5的记录 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() . X7 W4 [+ G5 W- V) _* i- U
6. 高级查询 条件操作符 3 P$ x1 d( C( W
- $gt : >
* I. q. Q( @6 K- J9 _- h - $lt : < & H! j0 D, E) L) n
- $gte: >=
/ H: \* V |. z+ R7 W: g6 F+ T - $lte: <= ~, p( s0 q: k# {9 D. t+ K. ]
- $ne : !=、<> # B. ^2 n7 ]" _1 @% S
- $in : in ! [3 W/ Z" y; {7 X- n* @- N- m( \
- $nin: not in 9 c- c6 @+ T: B
- $all: all 8 d1 Y3 f2 l7 K6 S/ f
- $not: 反匹配(1.3.3及以上版本)
复制代码
- u" a' D8 r: ]* m1 e% O/ u& {1 B K5 e+ b; Z9 J
查询 name <> "bruce" and age >= 18 的数据 3 B6 I% L: }5 a0 v& v9 M
- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码 # P6 [* W8 P. R/ p0 j/ @; V
0 j+ S2 q \7 q7 x, \+ N' R查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
* j2 ?' A- m& z7 N5 W- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码 , W$ K" f+ X0 i3 _
' i+ p/ r, p! g- P E, t K1 Y1 c
查询 age in (20,22,24,26) 的数据 ) [: R2 \" E2 e8 m
- db.users.find({age: {$in: [20,22,24,26]}});
复制代码
4 A: p- ~! q) c$ N9 l) z
+ w3 q# K) f+ e( [查询 age取模10等于0 的数据 3 ?8 k5 d9 i6 K# g# U
- db.users.find('this.age % 10 == 0');
复制代码
0 S- U7 e/ |6 R9 s W; h( a: p或者 - V. r# p) r' D3 ]9 x
- db.users.find({age : {$mod : [10, 0]}});
复制代码
0 \4 Q' ` p8 K2 R: g, C/ A6 x, ^. F$ f7 M6 h
匹配所有
. D$ Q! Z% X7 `- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码 ! ~5 {* d4 Q. {! h" @
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
2 |' A/ ?9 g% a3 c3 P* v可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
0 I& b$ X/ ^+ y2 T( d) c' g/ w8 F& q3 j. F! `( z5 x
查询不匹配name=B*带头的记录 . J+ t1 U' q. k7 D0 j3 S
- db.users.find({name: {$not: /^B.*/}});
复制代码 ) N2 N! \& x+ K4 b, I) u3 w$ d S
查询 age取模10不等于0 的数据 " `1 e, j) _1 @" g6 D( Q; A
- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
8 x: i; h. @! H
% s5 E- p# y& P7 A0 s" T#返回部分字段 & a) s) X2 X7 y+ f+ M
选择返回age和_id字段(_id字段总是会被返回)
! g9 x u0 `0 ~: r" A$ `7 ?9 X9 S* P; @+ T- db.users.find({}, {age:1}); 3 N8 t" P+ n: k
- db.users.find({}, {age:3}); * X- D" h% F. `) c* l
- db.users.find({}, {age:true});
3 T0 d% m4 e* D4 @! |2 ~) ? - db.users.find({ name : "bruce" }, {age:1});
复制代码 * s0 C8 `1 s4 I
0为false, 非0为true
b% j {/ q4 V O, h9 o: e4 A. T H% ?0 p* c6 g
选择返回age、address和_id字段 . {* D# \5 w6 o) R( c8 h
- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
$ i. X1 S' N4 _: h3 \' S2 \3 ?8 F3 B: K- T+ U' F2 N, f8 n; A
排除返回age、address和_id字段
2 Q8 M1 G% R& T4 I" I5 U- db.users.find({}, {age:0, address:false});
* N/ O" |5 t3 A1 e K - db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码 ) l' n/ r1 d+ ^' Q+ [" K0 f: S
' J U6 v* q5 N# o0 L) n% C数组元素个数判断
5 p* @0 ]/ o5 P3 `' y2 @3 E对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 % A; p& s; }, ^+ L
匹配db.users.find({favorite_number: {$size: 3}});
# m# R/ [. U. S" s5 V9 ^4 \ ? I不匹配db.users.find({favorite_number: {$size: 2}});
' z" e1 P# ^. z, a! ?9 q7 t# ~4 H& Q8 i! \9 |! w
$exists判断字段是否存在 $ h7 I0 J. z; P7 x" T I
查询所有存在name字段的记录
2 w! z. T! s7 i" I0 }- db.users.find({name: {$exists: true}});
复制代码 0 w# f& p2 O4 ?3 S. D( Y5 X# V( b
查询所有不存在phone字段的记录
! ~: A* ]1 `6 ?1 b/ ~- db.users.find({phone: {$exists: false}});
复制代码 + p- q" X8 h- ~( ^3 |
1 M- A' d# v! w0 l+ p
$type判断字段类型 # T. N- L6 B1 }" A; S- b) @3 [& N; v
查询所有name字段是字符类型的 0 R- g2 `, G/ r$ Y0 o; @
- db.users.find({name: {$type: 2}}); + u, f/ R1 X# ?% \6 E5 n: ]
复制代码 9 n9 o) h3 s, K) ^* \4 Q9 t3 s
查询所有age字段是整型的
3 J p- O( j9 F- db.users.find({age: {$type: 16}}); , T# L& K$ W* F0 m
复制代码
& c- N) _# ?" _8 L对于字符字段,可以使用正则表达式 5 U: f. Q5 b+ D6 x9 A) a7 I
查询以字母b或者B带头的所有记录
+ Z/ k6 j% q2 Z- db.users.find({name: /^b.*/i}); 5 t5 o& j0 O" S, L6 I
复制代码
, g2 |+ X! W) h' |& w$elemMatch(1.3.1及以上版本) ; ~$ \6 T4 m" X* F# ?; }5 ^
为数组的字段中匹配其中某个元素
7 P4 T: {7 f4 a2 ]# _/ J9 w& [+ k M1 T u) a1 U
Javascript查询和$where查询 , R, O x* k9 Q& w
查询 age > 18 的记录,以下查询都一样
5 L5 ~4 I) B; d& F- db.users.find({age: {$gt: 18}});
* o. _4 p: v/ n- x# ?0 p& s" U3 }$ W - db.users.find({$where: "this.age > 18"});
9 Z; ~9 v$ [: _6 ` - db.users.find("this.age > 18");
; {7 f8 L9 ]0 B U0 A0 R5 l. Q - f = function() {return this.age > 18} db.users.find(f);
复制代码
+ K1 w4 B. `5 S3 o& ?! z( x f
! S+ h) _. L7 S排序sort() 0 I$ D9 R# U, Q* o- G
以年龄升序asc
& r( |( c" M1 Y+ }+ x- db.users.find().sort({age: 1});
# r4 ~# c5 i/ h, D) X8 a
复制代码 9 e. M! k0 Z3 w. k M5 U. i% u6 ?
以年龄降序desc 5 _9 y! g. G2 P K; ?
- db.users.find().sort({age: -1}); ! m1 g p' W a" U% S9 U
复制代码 % j! A5 L/ x: d8 ^- z+ {" X
限制返回记录数量limit() 4 J/ f) o9 L) y' q% I# \0 T
返回5条记录
; b! c9 j0 t3 v6 w& @! t5 `- db.users.find().limit(5);
! B* r7 D+ o. u7 V# u" z0 v5 a$ m
复制代码 3 D# x3 n1 X5 x8 v ~3 r; l
返回3条记录并打印信息 2 x0 e7 e) y" n) X8 W
- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
/ @; }0 K+ C7 d" r( ]
复制代码 ) u$ b. U u Y8 j
结果 L+ H; L( a Y0 }2 i l
- my age is 18
5 e6 P T" B2 m - my age is 19 7 ]+ l; j. B7 `0 l+ M
- my age is 20
复制代码 # E% M& l" g: j2 T
[ ^# V' l7 E. Y
限制返回记录的开始点skip() [+ d7 J$ u: C% ?5 U- X9 X
从第3条记录开始,返回5条记录(limit 3, 5)
8 P5 {. [' I* K8 f1 {0 W- db.users.find().skip(3).limit(5); + q5 g, G0 C, R- ~3 k2 ~+ c
复制代码
4 C$ W. k7 \( @' m& D/ [! R查询记录条数count()
; R( {/ s3 D! `" \1 ]7 Fdb.users.find().count(); - w `* W' e/ _6 W4 \1 W
db.users.find({age:18}).count(); 1 @. M9 p1 @+ G4 a
以下返回的不是5,而是user表中所有的记录数量
7 G7 I! J% [( f" L4 Bdb.users.find().skip(10).limit(5).count(); 8 U$ ]3 A. u i2 Y* c7 C( }# I5 m
如果要返回限制之后的记录数量,要使用count(true)或者count(非0) + Z z/ K3 K8 e4 D6 _8 g
- db.users.find().skip(10).limit(5).count(true);
复制代码
. p: ] F8 J7 E0 S- ^7 s
6 c0 _, R4 r0 p, ]2 X分组group()
) ~ A Z4 h# f/ R2 F假设test表只有以下一条数据
1 B5 d! O4 X+ a' e" P$ M+ M9 F0 z; g- { domain: "www.mongodb.org" ( x1 f' V8 }- z# Z4 r
- , invoked_at: {d:"2009-11-03", t:"17:14:05"}
0 i7 o0 d# m! O0 Z( l8 M - , response_time: 0.05
1 A* T! I. E# e/ X' m" J - , http_action: "GET /display/DOCS/Aggregation" 0 E, H6 C' D" r. i" s
- }
复制代码
) }; f' l5 a( l0 L: s6 S) o使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
/ ?/ H9 ?7 Y8 D" c- db.test.group( " a `8 g7 s7 O1 z# K' R! d
- { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} % F9 k, Q) R/ K( v
- , key: {http_action: true}
* _( J# q0 [1 F" C+ L5 n/ H, O - , initial: {count: 0, total_time:0} 3 u2 b, e% V6 o Q
- , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
1 I* j6 y9 {0 P% H2 ] O5 j- O - , finalize: function(out){ out.avg_time = out.total_time / out.count } ' }9 c6 g) }9 d! g+ i- U" L! f, H
- } );
1 P+ h4 `7 D+ D1 N! f - * H" k4 ^# g. D* e) g
- [ $ e+ k' J2 X0 l: k% u* w& Z; u
- { & X3 K8 W- f! z2 f+ r$ }
- "http_action" : "GET /display/DOCS/Aggregation",
/ R* [1 t0 z- b. x3 E; s - "count" : 1, 9 O' |% v2 m$ X1 Y
- "total_time" : 0.05, & V$ q' ~$ d8 Q1 B7 Q
- "avg_time" : 0.05
5 d, L& x! ~( `, V! t2 u) X! p' J - }
0 X; O' {" C$ g. K f - ]
复制代码
. X0 }7 \( v7 L5 g3 |; H' Z
8 r9 S# T% y. z" s5 M- z8 h0 [4 N
. P6 Z+ {8 k* W; W1 TMongoDB 高级聚合查询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
$ u) v! N1 {, g6 p4 T
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码 1 |# |4 {7 q) l ~& ]
5 \) k5 ?0 k' K3 s
' A3 A% w, q$ v0 p# @+ a. @1 X相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 - distinct
( J" V# _6 K2 n' _+ G
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
7 C* H' o) W1 l+ o! G5 P6 Y! S$ I' u0 M
6 O! H( a7 o2 _( U+ | 他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码 ; N. i! @% [7 D+ Z+ [3 F) `
# x9 ], ^# K2 I- H* D4 | 我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码
5 L T# h T U$ C- O
( J: A6 t- h0 R1 a& e 我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码 0 T& J- Y1 @8 h; v: h1 s8 |
% R; @; F% _ q% Y! p) j& q. f 输出如: - # }5 s9 Q' t; m* W9 r
- [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
* z# q$ ]: C: z8 t5 h% L5 c% z u( X: A, G. J8 b# I# _
F# w6 i" u# [) B2 R那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"2 F6 a: G: N ]8 t7 t- O1 p6 d
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2 n/ d6 _ m- k1 @7 P( u2 N - xmlns:context="http://www.springframework.org/schema/context"
+ m0 j; {% U; z( G& N5 B' }* F6 F - xmlns:mongo="http://www.springframework.org/schema/data/mongo", M" ]$ v0 H! t: `! {7 V, P
- xsi:schemaLocation="http://www.springframework.org/schema/beans
0 C0 l5 A( c( b - http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
- o7 E$ ]3 {# e! v" f2 ~) S - http://www.springframework.org/schema/context
7 H5 K8 x4 K% Z c% | - http://www.springframework.org/schema/context/spring-context-3.1.xsd l( E7 ?% Q4 x
- http://www.springframework.org/schema/data/mongo" U2 O7 H: |- F
- http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
1 A8 w+ p4 b) |( M& d) D' u - ) H3 @: X. |# }# @
- <context:property-placeholder location="classpath:mongo.properties" />
1 p& Q3 m! g* x! u9 X -
9 r0 c' ]- p. p: v% _5 J# L& p* C - <!-- Default bean name is 'mongo' -->
4 p/ r- B ~2 F - <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />, B4 U2 O ]4 }% M( t
-
s& r# F6 ?: N- {) b/ ] - <mongo:db-factory id="mongoDbFactory"
( t, o& X# C9 u - mongo-ref="mongo" w8 i- s) ^6 k( d H
- dbname="mongotest" />; P) d% E5 t, U6 y& J2 L6 W
-
) }1 b) o; Q4 j7 ?" A! c - <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
, Q) a# r1 m! D - <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
% n r9 N* T5 W! ]8 D+ f - </bean>
$ D; ]. M7 l+ Y - </beans>
复制代码
4 Y" d+ I; Z1 v6 ~9 E . J" Y0 @) v$ c; y6 f( k6 ]7 S
max和min的测试: - @Test
! D4 b' I4 y: R3 M: P1 | - public void testMaxAndMinAge() throws Exception {
# f3 c9 w/ Z/ Z# b- g0 R E! a- D - Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
" H* j& D* Z) s8 ?9 q - Person result = mongoTemplate.findOne(q, Person.class);/ {" f _* w* q! T1 \
- log.info(result);
, C+ h3 P% j% K( X -
. V2 M: o; C: J! u }" C - q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);6 V/ D: L, \9 Q( {% |' H3 ~
- result = mongoTemplate.findOne(q, Person.class);! N( r6 _3 `; `8 I+ o+ H
- log.info(result);
, A" W2 \+ o, ^. {/ P A - }
复制代码 * p% Z5 E; H/ w9 M! v
7 t/ w3 L' V% A* Y
distinct的测试: - @Test
5 l x: o9 a+ E5 P8 C - public void testDistinct() throws Exception {
8 ^- c( B1 _8 r" A! f# }% z; ]! W/ X - List result = mongoTemplate.getCollection("person").distinct("myFriends");0 d* O' ?; G# Y: d, ]
- for (Object o : result) { G( ?( j2 c8 M$ y' Z% Z; I
- log.info(o);
( x4 {, j+ D( g2 O5 j% z8 { - }
) b% f( J& d" @ - % j4 F; I0 |; T4 J7 B9 j/ s( m
- log.info("==================================================================");
5 b: F0 W: I6 ]4 t) s- f - Query query = Query.query(Criteria.where("manId").is("123456"));7 ~, _% H8 `. W2 O
- result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());4 w x+ k4 K. A t- b& D; W( A* h4 t
- for (Object o : result) {, o2 @/ _- E1 ]; A
- log.info(o);5 D) w" d! A9 C! Z$ J8 Z9 A7 `; I
- }
) S2 z' ~9 Y) y+ Y4 n7 P -
8 { w/ z4 _ I: X- Z0 i - log.info("==================================================================");1 L$ P0 g7 w( O& @, i# T4 e
- result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");% q: `0 R+ X9 P$ T6 |+ M* ^4 C
- for (Object o : result) {
5 ?- I% L2 Q8 v9 N) f, G8 J - log.info(o);+ ` ?) g* D; J. T. Y; g$ |: _
- }
; x) O# K& q% y0 i$ q - }
复制代码 6 i0 c4 a* a% y( `
1 o7 ?- J' A) e" f I0 j 输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
0 D" ?/ m1 F& Z2 ?. j/ n4 F - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
6 M q& R: z: M) j - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
5 W( S1 f* {2 u* N0 P7 V$ E - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
6 i4 q, P3 {( ^6 r3 Q: } - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni( D: J2 ~" r& K
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo- c ^- f v) y3 B3 k7 ^& ~! T( g; j
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 1234565 X, y9 w" l: M" E
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================$ r- v6 k' T- k/ N* x
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
; a9 p0 o' Y0 c3 @9 T m! S - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
7 Y7 y. ~7 h' r0 I0 Q) P - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789& I- @( Q2 K0 ]" U/ ]/ d4 o
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654' \1 A; Q8 O m" X* g
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
1 P- i1 S" n7 l7 _ K - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa" g* z" K5 A; p
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb3 A- ~9 R. J0 v/ ?! q1 r4 p) Q
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
Q9 Z A& [/ D - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www6 T- j W5 H- m5 ~# `' B3 c
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx' G% y7 I" B6 v( G+ ]9 F- [7 N
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy) C+ [9 ]1 r4 y8 _
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz4 c9 Y" S6 ~7 o7 o8 |+ d+ w+ w
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr2 z3 u# x& h+ Z$ N
- 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
复制代码 $ S) B7 n! ~2 U1 C
. [& @8 z4 ]. c; 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等信息。 5 ^* n! A) l9 `# s4 M
6 w# m# h) d! k' h! c6 Q3 O
3 G2 d+ w! l( f3 w3 F8 n |