|
版本一:
6 ]5 A( F3 ?( R6 D
( U+ H4 G; A3 R* J. Y1 ) . 大于,小于,大于或等于,小于或等于
/ _& k# K2 h# e7 ` r* x2 X. k" B
. z$ S0 w3 J- j" |$gt:大于 `$ V. ^* G- E4 d# _* ~" S
$lt:小于
9 L, O( u/ B' ~+ s4 a$gte:大于或等于
3 y5 y& g/ S/ G% r0 e$lte:小于或等于) U0 H5 j/ d( o+ [
" B" G/ S1 S8 x. E$ l% F6 a
例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value m& {8 m5 I+ j, m
- db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
' L Y" x# b: ? - db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
$ v( w- V5 d$ |2 S1 x' m) D - db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码 6 ^ G2 E- v# L1 g n( b
如查询j大于3,小于4: - db.things.find({j : {$lt: 3}});
9 s% |4 ?) K* S; b7 ^0 Z1 h5 A4 b. r - db.things.find({j : {$gte: 4}});
复制代码 # [' w+ @6 d7 U; U- S4 F8 h$ d
也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码 " n9 s. }* N2 o* T4 y
/ A9 o* I5 j9 K/ f- ?
, n6 `* z* A. e7 Z
2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码 4 k- a! P; c2 g2 s5 W/ A) Z' `
3) in 和 not in ($in $nin)
: A y g! ~! X3 J9 g; u/ Q/ j N3 P- C7 x" Z# Y& h, f
语法: - db.collection.find( { "field" : { $in : array } } );
复制代码
# g3 R# S4 G" F$ k3 W例子: - db.things.find({j:{$in: [2,4,6]}});
5 @' a" F- v: R2 k4 Y1 H+ V# J - db.things.find({j:{$nin: [2,4,6]}});
复制代码 3 D, [0 V- [ W8 Z% P' `+ f& k( ^
1 Z! e3 `" `9 q7 y5 y- ?
4) 取模运算$mod
- v5 Z% y0 }* v7 C. q3 A2 Q
) t1 k" b, {( E( P1 H1 X如下面的运算: - db.things.find( "this.a % 10 == 1")
复制代码
5 S& n+ k' J' F2 F可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
6 Z y+ w, ]! M2 I7 r) {; o
' O0 u/ E1 P# }0 J* Q7 Y5) $all
# o) b' w) Y; O3 i- R* y+ o3 S/ G' G. `0 k8 Z5 ?) l( N" e
$all和$in类似,但是他需要匹配条件内所有的值:# _$ f, y* W4 d: w. N4 H9 l
% N- {/ C9 o+ P, D# m2 l2 u9 ^% y, N
如有一个对象:
* W: S7 ~+ k/ @8 ?9 J
* \% M6 C, O* V4 X7 ]& x* A下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
3 J- K# M1 L/ m1 f: m6 U但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码 ) }3 |4 N. e2 n( Y) g, f- ^
+ N4 T' ?8 _/ s
6) $size
( z, ^8 @6 W* u9 ?
- ?4 {8 m; @7 l8 e; w$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:+ {% k$ z, Y3 s# ?8 G# \ @% K
; ]% a2 S# u1 A. ^下面的语句就可以匹配: - db.things.find( { a : { $size: 1 } } );
复制代码
/ c, U1 T7 e; `: S* v# E官网上说不能用来匹配一个范围内的元素,如果想找$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. . ~( {6 C4 H. k& p$ [( _1 }
7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回' L( \4 ^; v/ M3 h6 f2 [% Q0 x
- db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
4 n6 ?4 m/ h1 p0 c" v* z8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string7 P- x3 j, ?( ~
- db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码 " U! K- ~# e8 `
9)正则表达式
% @* M. b; ^/ D t5 W& S4 F9 l+ }6 O
mongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
& l" r8 Y6 ?+ F# n( ~10) 查询数据内的值+ z4 t: w$ u8 n6 B
( j/ E8 \$ O( p& m: U. k
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码
3 D+ y+ a" C @3 J# J6 ^9 Z. P1 W4 K% I11) $elemMatch
I9 J) u/ D# V) j# Z3 t! {9 d" w5 _0 p% l+ ?4 l: ^
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
, R0 D; a8 b3 r _' g' O3 { - { "_id" : ObjectId("4b5783300334000000000aa9"),
% e. a4 S& F8 ^ - "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]* b3 v6 H4 Y9 @
- }
复制代码
% L. P6 W5 p% `, X5 i0 t$ y$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )3 m2 K9 ]! ]& W. e
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
1 Q2 t$ g8 B6 m/ V+ Q( B j
6 l" J1 g8 D) e# q5 ]8 m2 k12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码 . _+ W/ j ~3 A8 r
举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码 . Y( }8 i0 A/ K3 F6 i k
如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码
; o; j# ?1 ?( j" d0 v& O如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码 % v8 o! A2 M) A8 H( }5 P* K0 @
下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
- Q, ~' y4 O9 e% @3 Z是不能匹配的,因为mongodb对于子对象,他是精确匹配。 ; ]9 Q- E& x2 _( I1 O+ P' m
13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );# r/ E2 S4 M" @& B* P3 b3 Z
- db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
, n5 Y$ m4 g! G F! t: _- \9 `0 _shell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin 5 h6 e& K0 A# ~: M, K. r
2 h0 [8 x8 ]4 C) Y& ]
2. #增加或修改用户密码 3. #查看用户列表 4. #用户认证 5. #删除用户 6. #查看所有用户 7. #查看所有数据库 8. #查看所有的collection 9. #查看各collection的状态 - db.printCollectionStats()
复制代码
8 h7 z. Y8 P! i8 J 10. #查看主从复制状态 - db.printReplicationInfo()
复制代码
% f1 f; A: S9 I' @ 11. #修复数据库 ( g i7 k* G* Q6 H; m0 N& i1 ?
12. #设置记录profiling,0=off 1=slow 2=all 13. #查看profiling 14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
* d9 S1 G- A! [! p6 }3 ~ 15. #删除collection 16. #删除当前的数据库 / R4 ^! _) t2 m# w* j% X1 R
2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码 ( j: h6 Z+ L% \+ |! N, {
2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
: Z0 C9 \ s' ^% r9 m0 c2 N; w 3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
7 X! L9 _. c3 `, h 4. #删除yy=5的记录 5. #删除所有的记录 ; {* ~. b: h9 M4 h1 O( ~$ `. M
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()
R5 Y2 }9 W' U) Y6. 高级查询 条件操作符 , W) X* B( ^8 O. s8 l' p. I* O
- $gt : > . N3 H5 m; G8 @
- $lt : <
2 Y* a C* l, N2 I/ O - $gte: >=
& ?8 E# c, X: s% k# E1 T2 j - $lte: <= $ Q! M4 k2 m+ }+ \3 C- T8 S+ P& g
- $ne : !=、<>
0 E7 R3 U/ b+ R& T) @6 Q# a - $in : in 7 P( Q( K# y. P# [' V$ x8 S/ Y; S
- $nin: not in 4 y9 q( S [+ T& _
- $all: all
C. E/ @5 d" P- t9 | - $not: 反匹配(1.3.3及以上版本)
复制代码 2 ]2 ]& l9 ?% b, C* R3 k
; N# I+ {) j5 c查询 name <> "bruce" and age >= 18 的数据 + p1 r; O! G* p. U6 f$ U
- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码 0 `0 g8 A' R: u
/ @' N, q8 I1 a d, u查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 ) F) n. e: p. R ^& w# x% b
- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码 9 m6 i6 Y' ?$ x* N9 k6 b
) J; P- Y$ X& V% [9 s' |查询 age in (20,22,24,26) 的数据
% w: M4 }4 J% i' y3 D- db.users.find({age: {$in: [20,22,24,26]}});
复制代码
0 N# r% f, W! n+ X& z1 I6 |/ j1 Q; w: P7 D/ R i8 V1 v+ N
查询 age取模10等于0 的数据 ) n1 M; h) i3 D% z) _
- db.users.find('this.age % 10 == 0');
复制代码
5 y$ y) w0 R7 T Y. x3 T或者
- }9 v/ {1 i9 V6 ?! y- db.users.find({age : {$mod : [10, 0]}});
复制代码
0 L9 e4 `, O9 k
" Y ^$ d8 d7 l4 |4 r- a6 x匹配所有
) ~ ^ m1 ?6 G3 G& u/ P# w8 J- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
0 W- c; q5 p K& R可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } ; A$ \# W: g7 U" e
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } / x3 z- I4 A& ^
4 D! t# n/ p( q% w
查询不匹配name=B*带头的记录
) ?! Q7 k1 F0 t& H7 D, r- {! a- db.users.find({name: {$not: /^B.*/}});
复制代码 ( l" [: C- h9 ^% n C# [
查询 age取模10不等于0 的数据
" f% M1 v% m2 @0 h( F: I& K5 c, m- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
0 ^- b1 d; ^( w+ p6 b: @$ B' `. |5 a
#返回部分字段 7 H" l1 ~; |2 U( {0 f9 P3 Z
选择返回age和_id字段(_id字段总是会被返回) : S0 E3 r% b6 r$ ~: G
- db.users.find({}, {age:1}); M: ?( Z; H$ A/ l; E
- db.users.find({}, {age:3});
# J% J/ K$ y! t& ^% ~9 N - db.users.find({}, {age:true}); 4 ^, @$ u* ]6 R7 T2 p
- db.users.find({ name : "bruce" }, {age:1});
复制代码
! c' q1 |3 O+ o* T0为false, 非0为true
) @) ]! d8 Z* p
! z3 ^7 p( x% }选择返回age、address和_id字段
! }" J8 B! {2 j- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码 & s5 _0 C. E$ G
* O7 A. ^4 t5 U
排除返回age、address和_id字段 8 y' ~+ z8 G4 O, i; a5 O, y
- db.users.find({}, {age:0, address:false}); , T A8 z6 M1 K, W, v8 e" c% o9 m
- db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
- [& E0 t7 @9 A" k( c
0 K- X( e; f1 q6 h' r4 b数组元素个数判断
# h: c# K0 p6 m: x+ d对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 4 P, L/ H2 i/ n- T
匹配db.users.find({favorite_number: {$size: 3}});
$ u9 D% ?" b2 Y6 G! e8 _不匹配db.users.find({favorite_number: {$size: 2}});
+ y& \0 e2 p; n1 G/ T! e
* C, ~3 x% ]. w2 [7 q2 p( s$exists判断字段是否存在
) H" T* P3 O7 i: T1 o查询所有存在name字段的记录 ) c: ?: p; K' c( \) R; k8 k" ~* Z
- db.users.find({name: {$exists: true}});
复制代码 1 o D7 r4 `) L; G- a5 k) _
查询所有不存在phone字段的记录 + g8 ^8 a- w4 t9 ]* y- D; c
- db.users.find({phone: {$exists: false}});
复制代码
% I% O. C9 [6 }1 z- Z
3 C _) F- z+ q* V/ E+ Z( L$type判断字段类型 3 Z! \, N; i, d+ k4 \! K
查询所有name字段是字符类型的
2 S f) X0 s% Z! _% x( A- db.users.find({name: {$type: 2}}); 2 F, S! z+ L# p1 ~- U2 ]1 C5 n3 ?
复制代码
+ Z% z% V9 H# l( f+ A3 z查询所有age字段是整型的 / ]5 P2 C% G3 _
- db.users.find({age: {$type: 16}});
b f' O6 V8 j* O2 M4 D2 b
复制代码
: u+ Y6 E8 n4 P, T+ n对于字符字段,可以使用正则表达式
0 [) v/ h" N0 r+ J+ y- L; e: e查询以字母b或者B带头的所有记录
# Z' z9 ?. a( y @8 b# A- db.users.find({name: /^b.*/i});
( N7 z% m# P6 V9 s0 J
复制代码 * b0 X( @8 {7 [7 D3 q; a3 p4 y
$elemMatch(1.3.1及以上版本)
: ?6 L! K6 n5 h! j为数组的字段中匹配其中某个元素
# H: x* O" |: r# J
; g. y6 Q' k' ~Javascript查询和$where查询
8 m! y( ]3 D0 C6 e查询 age > 18 的记录,以下查询都一样 6 |7 d6 |1 v( |1 y, E# W
- db.users.find({age: {$gt: 18}});
4 I; h3 Q2 J( o. P) X - db.users.find({$where: "this.age > 18"}); : `* A5 H5 |& b# `" O0 j
- db.users.find("this.age > 18");
: _3 e, G: p: k3 P - f = function() {return this.age > 18} db.users.find(f);
复制代码 1 ]7 y0 | j! f' G5 [$ N- E
1 O W6 [3 N& w排序sort() : q9 b ^% z7 ] b5 ^! z6 `& v
以年龄升序asc
1 O0 F: t/ p2 @- db.users.find().sort({age: 1}); 6 r l7 F7 {. R p
复制代码 + i" ]- p2 ~$ }( a/ j" a
以年龄降序desc
% x* z7 h. }3 I7 N! ]* E6 \& I- db.users.find().sort({age: -1}); 3 S* o# j2 V, Z, d$ C# ^7 U
复制代码 ' C2 Y9 H( o6 h* w3 c9 e3 W, k6 C
限制返回记录数量limit() / p: b% Q8 g/ {% `
返回5条记录 2 T) E, V4 R h9 m& {$ f ]
- db.users.find().limit(5); 8 k; r9 f! ]/ m/ u' r# z
复制代码 ' } O' j" g) Q- [" Y w
返回3条记录并打印信息
: @1 f6 G, Z) x3 ]8 _- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
1 E% ~7 D# g1 J4 a
复制代码
- h6 [# c/ y9 V$ w% ]1 p) i2 Y结果
8 D4 ^+ b+ r; }! U7 F2 X- my age is 18
' _8 l# H4 z0 E Z- V - my age is 19 ! V7 ?! e1 f; `3 q3 J
- my age is 20
复制代码
4 I/ E) A% M6 I" G! a$ X; S& m3 G. l6 ^1 {
限制返回记录的开始点skip() # c( a! Q, Z6 J( `5 f
从第3条记录开始,返回5条记录(limit 3, 5) 7 t' B$ ^$ {. v" L# ^( o# S9 v
- db.users.find().skip(3).limit(5); - Z" t) H* K9 T- F' z* L5 ]
复制代码 * z w) ^) w- F3 \
查询记录条数count() 2 S4 a3 ]" j& U' ~# F
db.users.find().count();
$ B8 t' z/ h2 c# D& c* Adb.users.find({age:18}).count();
. [$ u. V/ r2 Q3 S9 y以下返回的不是5,而是user表中所有的记录数量 1 T: G' l: L9 I/ o) Z1 Z" I4 H) O
db.users.find().skip(10).limit(5).count(); + L3 o+ f4 p; ~0 F. s0 Y L
如果要返回限制之后的记录数量,要使用count(true)或者count(非0) ' d6 V8 X# J D9 P s
- db.users.find().skip(10).limit(5).count(true);
复制代码 7 \' x1 s1 _- i5 o) U+ U" A+ H- [
3 e# x( d. k4 `& \0 \
分组group() 0 D* ?/ z/ _* k% F8 P: l0 M
假设test表只有以下一条数据
2 n+ S" B5 M9 c0 a: Y+ B$ X# q- { domain: "www.mongodb.org"
4 `/ @2 Z8 ?- ~3 V - , invoked_at: {d:"2009-11-03", t:"17:14:05"}
- t q. P3 }$ T' t" n - , response_time: 0.05
) \& f" a, V# O# W: Z7 t0 C - , http_action: "GET /display/DOCS/Aggregation"
8 o' p& \/ u8 m4 [, M6 D6 K. p - }
复制代码 0 w0 r1 D6 T. h8 Q/ h+ \2 P
使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
, i1 e( Y, K- P G( p5 C" N- d) ]9 K- db.test.group( ( n3 B" D+ a4 Q4 I& \
- { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
, j% S0 z5 l% K4 c9 M - , key: {http_action: true}
/ q$ F: U- I1 a% p2 G - , initial: {count: 0, total_time:0} , d5 s7 P" D; e" Q6 e
- , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
9 ~8 d* b+ m$ P# H8 z6 O2 ` - , finalize: function(out){ out.avg_time = out.total_time / out.count } 7 K* l7 L0 q7 S1 z: O
- } ); ! B- g: u" ]6 @2 r7 U
- 4 v7 ]. k2 e8 u$ W! x
- [ ' ]' n1 S! e" ]9 }6 U9 q
- {
' V1 f) `( F$ y - "http_action" : "GET /display/DOCS/Aggregation",
7 s L2 H- `2 @) D. K9 E6 `2 C - "count" : 1,
0 p/ W) l0 `0 R7 C* ^5 \' } - "total_time" : 0.05, ! S, P. n r Q/ k! y: ]" Z0 \
- "avg_time" : 0.05 : Q. B7 Q7 o3 k
- }
$ {: {3 }, Y+ C" W% [; L- s - ]
复制代码 , U: l- x) F* z! c9 ~6 P. W
0 b" U4 \! m- L4 k- D* A) j! e/ b+ B
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吧。 我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
+ c2 F( _% ?% \1 `6 y# N7 _ _$ t* T: J5 V; |; j
1 H# q; n* B4 @% O0 i: P2 P相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 - distinct$ g/ ?- I, Q, |% l. t5 [0 c( |' a( i
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码 8 M: X: N, @2 n4 c
4 J" n! F& O8 N 他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
; P( V* Q. _* X" j! f+ j0 F& R; x; C$ p( S! \" k. } R
我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码 ) L0 I; s3 A1 x/ \; u
' S. b- c0 i6 p2 c5 x5 ~# @; J
我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码 * z. @2 Y+ |5 j9 Q7 U
3 c: W4 Z2 Q9 O' y
输出如: - ( g0 f' `1 {, p
- [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
' }: I* f/ N2 s5 v9 V! j3 }
' T+ W G+ S2 C. w% l" k* x$ K( r0 ?0 e$ K& _% g
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"6 X. Z" S3 k C# O% d5 {
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
6 ^9 W- J9 Y( I - xmlns:context="http://www.springframework.org/schema/context"- n& G, m- B7 a ~
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"4 B; q) Y: R% f
- xsi:schemaLocation="http://www.springframework.org/schema/beans; z5 ?, p q M& o
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd1 p( m6 Z6 m/ W% H6 `# i
- http://www.springframework.org/schema/context; _1 _7 a- }, | k" Y: k8 J2 Q6 U! I% h2 t
- http://www.springframework.org/schema/context/spring-context-3.1.xsd
; W0 t) O. `7 i0 `( s' s - http://www.springframework.org/schema/data/mongo2 G9 `& K( O2 u' b- ]
- http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"># Q) ]+ f, d6 [& d% R: ^* p5 j7 k
- . k6 D/ P( Z2 p0 R4 S- s
- <context:property-placeholder location="classpath:mongo.properties" />
2 q% ~+ b' Q- _0 O) f -
( f& T" m' J/ s# t; I2 [7 r+ t - <!-- Default bean name is 'mongo' -->: F* Z9 T P0 w' S/ n8 T4 q
- <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
7 d* h% y2 y& a7 I) h" g - 7 D' p) C% A) h% G Y
- <mongo:db-factory id="mongoDbFactory"
5 Q% C$ i$ Q! [6 g - mongo-ref="mongo". m( g, y: P2 U- i- Z( G
- dbname="mongotest" />% \% w- f8 m ]! f) e1 l
- , v+ X9 w% C# z8 O, \
- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
! i6 {, K+ M5 w - <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>6 y1 Q) i% r) z
- </bean>1 m: R/ @3 L# D; D# j
- </beans>
复制代码
, s& w C9 f: A3 w3 _
2 k3 k0 h% _3 Y max和min的测试: - @Test
0 M# V# L' ?1 t9 ?$ O3 P. h( | - public void testMaxAndMinAge() throws Exception {
( e2 A) ~9 D- j, E9 \2 r - Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
3 G- N" ?- V- J# z9 D$ C - Person result = mongoTemplate.findOne(q, Person.class);
6 k0 ?3 c$ l3 ]0 i) `/ G - log.info(result);+ W' i) x8 n! c: M& v
-
: J/ B' {# R% W8 p' V& Q - q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
( Q3 a" }0 `3 \% `" N2 ` - result = mongoTemplate.findOne(q, Person.class);
0 l0 \" v/ j ]4 b: s - log.info(result);
' R2 ]( T5 j H, H, z6 H+ X - }
复制代码
% `+ S# h6 e6 a9 J
% V9 ?" A3 l& E) E7 ]1 j distinct的测试: - @Test0 h" M L% T% q9 A/ s
- public void testDistinct() throws Exception {
: ~8 n/ n! I9 G7 o" x& i$ |- Z - List result = mongoTemplate.getCollection("person").distinct("myFriends");4 o4 [$ B+ d& l% X. `0 o* }
- for (Object o : result) {, g% d8 i! d, w8 I: W n
- log.info(o);3 t6 o4 f! v9 j |. x5 \' d
- }
5 M0 T# ^" [7 E; P3 N -
/ u/ {" F" M' a c: v - log.info("==================================================================");
: G3 E$ d; w" f0 ^ - Query query = Query.query(Criteria.where("manId").is("123456"));
6 u8 ?; T8 t" }# k$ m- u - result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
3 a* i: @: f* m0 n - for (Object o : result) {
. b X% p& G# Z3 U - log.info(o);1 p: U( C& P6 e: G, D! T3 R- h
- }0 O7 I3 K5 l( I7 Z
-
( P. ~/ ?* {1 ?: ?9 P - log.info("==================================================================");; p( ^" A! Y+ O# G7 B4 l
- result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");' g6 R" j9 @8 ^. u# {! }- v
- for (Object o : result) {
( p8 G2 _7 a) H8 J - log.info(o);
+ d# ~, `) E+ \) m$ @( {. r - }
6 c4 c- I% O E6 R1 C* `, h* r& R' [ - }
复制代码
. i [8 z/ p/ x
6 ]: B A4 {9 w7 c0 f2 p 输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
3 [6 w5 V' V+ q' t/ t - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678. I- y' C5 x4 H, W9 S( t
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
5 V( N( h9 @5 E7 ?* c" W' I5 N ] - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654) z2 v* a+ R) [7 q- `
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
, O2 q3 j9 F1 V+ ~, H/ k! q, }; N - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
6 b" j# w0 H8 j g- G+ _ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456" r- @; I( B$ ]5 l* w2 }
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================5 q/ w4 j9 i% M( \5 A. p# ^3 g: S
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
# U: V5 ~) i, N; `. d1 `$ ?, } - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
1 V' F; L9 {# d3 o7 s) m. c# P - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
. ]$ i9 `5 m* M% C8 j) ^ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654( H8 h$ f4 h ^0 F* H
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
) Y6 ^4 i/ a, s. R- M9 s( J - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
g" X9 `; U4 J# |( x0 t7 @6 ^ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
3 \' Q# s& J/ d+ i2 b - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
: q$ k- v% \! O; n* Y4 ]1 V. N - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
6 T4 O) j& W6 b3 T+ W0 H - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx2 G) p; x) v7 _
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
2 g7 ?! I y; B5 a k, C# d - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz' }* i( l; @, q! ^- c, F
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
) }$ r/ I2 q% g; Z3 `( X4 B! [ - 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
复制代码
* Y w1 Z8 L% E. o3 b8 q; w" `3 h8 _; C2 t! b
这里我要特别说明一下, 当使用了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等信息。
; }3 i" c# o* b8 _3 ?! e! t8 m0 w" [' P
* N+ c0 `1 x+ J" u, u- H/ G
|