|
版本一:: m" Q" a* r6 {4 Z" E
, h( S; B1 d$ X; i8 A# S: {
1 ) . 大于,小于,大于或等于,小于或等于
+ `4 U4 G- [0 W5 g7 c4 A3 ~+ T O) o5 ], ^3 Y, d3 Q7 p! X
$gt:大于0 n. h4 Q( _7 O( ]' Z+ d1 G* T) P( m
$lt:小于' Z* `! o- Z/ G6 t) O$ Y
$gte:大于或等于* L. R6 W& i3 b" j
$lte:小于或等于" e5 c( U, H+ H7 ~0 v9 M9 v$ @
6 V$ A U+ c! p# H/ i9 Q
例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
* y: C6 R0 k) J. Y* h. a - db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
0 D8 l$ E3 F9 C" I - db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value
! J- U' J% \) S4 k/ r# O - db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码 # \5 |$ H4 j: l0 T, E
如查询j大于3,小于4: - db.things.find({j : {$lt: 3}});
+ L! Q0 Y- s' i - db.things.find({j : {$gte: 4}});
复制代码
- y! n+ E9 v; U2 f; |# A也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码 ; d: A1 i# o. h% i
, [9 v7 O# |/ \7 D" ^
6 g. u# a: r3 x7 S4 `$ X! ?# v
2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码 $ A% d5 k- S$ `
3) in 和 not in ($in $nin)6 ~. Q8 q9 x. @6 c' O8 _; H# c5 d
7 E4 |7 i% O1 {( Z* M Y6 [语法: - db.collection.find( { "field" : { $in : array } } );
复制代码 1 m' Z& ]* g* ~7 {: y5 l9 l; ^" c
例子: - db.things.find({j:{$in: [2,4,6]}});. b6 J B: q! X
- db.things.find({j:{$nin: [2,4,6]}});
复制代码
U" O1 B9 k) r
5 \8 z) n" g0 f4) 取模运算$mod0 m1 \4 c# x* Z8 |) J
3 c6 ^8 [8 s( J* U* i
如下面的运算:
- db.things.find( "this.a % 10 == 1")
复制代码 ) B% J) a/ u+ `, s, W' N
可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码 # g* T5 S+ t0 q5 _2 \7 q& x
8 q' s- j2 v& t4 H& y, X
5) $all
, |; q' Z% ^. w( p d$ ~1 V$ e" K) Z$ b/ w: K7 [7 J4 O
$all和$in类似,但是他需要匹配条件内所有的值:
4 z7 i1 a9 z) b
; A f5 Z; I5 f# d如有一个对象:7 p5 z9 I! ]) ~+ i" i
9 S+ M) S2 v& y' g N* _6 o下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
& k! T7 f ?" R但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码 3 m1 b+ c* g+ N. A. G$ o1 c
/ W: ^. L/ N2 [
6) $size, d- R& @, A0 ]* R1 Q+ f/ Y
# L3 t: ^0 K# N3 t& I
$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:$ ?( a1 O6 g6 p- X( G
( e1 \) l; O" c: Q1 \9 ?下面的语句就可以匹配: - db.things.find( { a : { $size: 1 } } );
复制代码 ' d' C1 i, l6 J5 ?1 d& [8 j
官网上说不能用来匹配一个范围内的元素,如果想找$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.
( f+ I1 d/ |% `8 E; T7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
# s/ a' y' T5 c1 d - db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码 , A. k9 U4 h6 F! H5 @% ?
8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string1 E- X m. j4 e" x
- db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
, m: ], [: F# k" ?6 E! S( G! X/ R1 k+ L9)正则表达式7 {( i$ g. q; e& z: S
! t8 Z* N6 ?% @" L: R
mongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
4 D4 d' A5 U2 O% a10) 查询数据内的值) i" }5 ^7 s: @- ^1 b$ }+ L& a
8 K" N$ L0 x' G5 l下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码
! }; ?" a0 O B8 U8 G" ~3 J11) $elemMatch
4 H1 {7 J% o0 E4 S9 w( a, s7 k; |' Y& O
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
7 J2 y b1 y* n6 c/ j. {; q' X9 N - { "_id" : ObjectId("4b5783300334000000000aa9"),
$ {( C6 x& A* I( ]) F! x* E0 L - "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]+ [' y, o P* |/ f) o6 y6 G
- }
复制代码
3 U! c. N" q: U+ P: l: F: G$ ^$ _$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
8 B: Q+ i" X; }& \) k: P$ L* e$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
) A+ n' O8 }- Q8 y @+ y7 n3 L0 O- t
12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码 1 A6 s# {# k2 z6 y% o8 p' U5 U# F* \! A. m
举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码 % M* G* P, e8 j0 Z% F
如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码 , W3 E8 x' j' D( J
如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码 4 Y' ` }3 e6 l' K2 f( ^9 d4 y$ {5 Q
下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码
4 B6 f! v6 S; ` [; E. j3 Q是不能匹配的,因为mongodb对于子对象,他是精确匹配。
0 A3 F5 G7 M4 I) l" J& b; O13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );& U8 a: Z3 j0 \0 N
- db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
) C9 G! _( _5 } V; ?, cshell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin 6 ~! v; S, A" H6 j; a* j
5 M0 S2 i! X6 W8 h: B3 w3 o 2. #增加或修改用户密码 3. #查看用户列表 5 r1 b7 E# r) n7 H' Z. O0 ^
4. #用户认证 5. #删除用户 0 o/ K! Q* d2 H6 w" Z. m/ `4 l# p
6. #查看所有用户 7. #查看所有数据库 8. #查看所有的collection : X; b3 \. m8 V& p) ~; `3 o6 |
9. #查看各collection的状态 - db.printCollectionStats()
复制代码 ]2 m3 F' H0 g0 R# i
10. #查看主从复制状态 - db.printReplicationInfo()
复制代码
, [3 G" Z' P" T' F8 X 11. #修复数据库 12. #设置记录profiling,0=off 1=slow 2=all 13. #查看profiling 14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
8 Y& D W8 e2 N 15. #删除collection 16. #删除当前的数据库 0 A g; h# v$ U" f6 h" ^% u3 E
2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码 & F6 ^3 _4 k7 J: r# c. j+ r7 \3 {9 v
2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
& {) M3 R! q; q' \5 o( Y* x/ p4 O 3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
! j4 X& t6 X5 J( \1 b5 a4 d' } 4. #删除yy=5的记录 5. #删除所有的记录 " B, P) t1 h& ^+ i: C) R' Y
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() 7 i5 H: b4 U+ n) d a8 r
6. 高级查询 条件操作符
% \9 H: Y* P9 D) M" [- $gt : >
* p" T& |; \) Z$ E# q - $lt : <
% d0 G% x% k* T7 |+ _5 J t - $gte: >=
$ P. \! N- p/ v0 M - $lte: <= 3 k9 ~! D( Q0 b. f! u
- $ne : !=、<>
3 {+ b( `5 @0 I - $in : in
* d* D* D8 a4 @. ^4 P - $nin: not in
* k" a- ^( b$ ?+ P - $all: all 6 e5 P1 b! y0 L
- $not: 反匹配(1.3.3及以上版本)
复制代码
+ r, P+ k7 F4 o/ Z; B1 @1 S1 ?! v- J2 {2 n
查询 name <> "bruce" and age >= 18 的数据 8 {5 j/ f5 H$ p4 h* [. O4 z
- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
; L8 Z4 Z/ B5 }8 c p9 ^' t, q9 C2 [8 P, ]1 @' y
查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 8 ]5 @, X# [8 z0 ?" l ^/ _
- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
A3 t- q6 q+ |5 M( z! u7 ]% ^: r
查询 age in (20,22,24,26) 的数据
) l) a" D; w9 C7 E Y! n- db.users.find({age: {$in: [20,22,24,26]}});
复制代码 4 {* X' n V" L% k( v
6 R, {! L6 m! S! Z& m( e
查询 age取模10等于0 的数据 9 s: }" a; q8 [" g/ O$ l! n0 Z
- db.users.find('this.age % 10 == 0');
复制代码 3 K* D! ~+ O: M3 {3 v
或者
9 w8 N4 A$ Y- I- m$ e( ]- db.users.find({age : {$mod : [10, 0]}});
复制代码 `9 f# ~ U* |0 N2 \. I
7 s/ l; {8 ^' A' X匹配所有 $ q m4 |, K+ s# o8 T/ D D* Y
- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
) S+ v {! }! s* [2 C8 a6 ^可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
3 K, F* Z3 B! d J- U可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } ' Y+ j, V g5 `* R
. Z9 t0 V; K! |. ?) e$ B
查询不匹配name=B*带头的记录
! }7 Q# g( I; x9 P: U5 m9 {- J- db.users.find({name: {$not: /^B.*/}});
复制代码 " t+ p0 T B9 Y. b
查询 age取模10不等于0 的数据 : n8 V& F4 m7 ]& c8 {1 z5 Z; B
- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
! X1 [ Z9 b2 m/ [' K
* J5 n! Z2 s7 I8 W5 ]3 x; l7 a#返回部分字段
9 ]8 N; L" O1 N' T; l& b; `选择返回age和_id字段(_id字段总是会被返回) ! [" ~' b1 U t ^* I
- db.users.find({}, {age:1});
" b. ~- Z5 i8 F3 K1 [ U2 I& b/ K - db.users.find({}, {age:3});
# x6 P4 C* W; P! D - db.users.find({}, {age:true}); 1 O4 W% q2 O$ `
- db.users.find({ name : "bruce" }, {age:1});
复制代码 8 w" G6 L2 R- V& s% j
0为false, 非0为true
8 R& R- I% C) a; b7 _" F; w( F( n
) M6 W# ?- f; b( \选择返回age、address和_id字段
" |# g0 {; f8 |- u' R8 }- ~ [- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码 0 W- S; o: g. l) s7 s5 p% C6 b
, y/ u0 B e- p) v8 L( A& i* K7 e排除返回age、address和_id字段 . x7 p" y0 N) O' v3 Y9 ]8 B
- db.users.find({}, {age:0, address:false});
1 B& F" W1 o7 T' o! {% p' \7 E( l - db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码 " Q+ z4 M5 n7 n L
& I1 X/ \2 p" ~3 O数组元素个数判断
; n4 ~2 O. J5 Y对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
2 e/ f" t( C9 K7 _' {匹配db.users.find({favorite_number: {$size: 3}});
- Z2 K5 D* c# ^. I R o不匹配db.users.find({favorite_number: {$size: 2}});
7 O( ^, b# x9 }# @: {- N3 _3 U4 r$ X9 @
) l4 m$ b; o8 C" v: Z, v$exists判断字段是否存在 4 E& n8 p) _/ _: G
查询所有存在name字段的记录
' P3 g4 T2 W- Q) o- db.users.find({name: {$exists: true}});
复制代码
* \: F0 q+ p H. u查询所有不存在phone字段的记录
) y& ]4 m3 x; \' s- db.users.find({phone: {$exists: false}});
复制代码 ' n+ E8 F) D$ q
, S* T3 ^6 `: f8 |! k2 I# Q
$type判断字段类型 ; u# w; B3 \, C
查询所有name字段是字符类型的 8 `! `% ]* D; S5 G) m0 V
- db.users.find({name: {$type: 2}}); 1 u _7 e; l$ b P: ~& p' Q
复制代码
3 m+ u8 w2 {7 V( I# O/ i3 S; g: B4 {查询所有age字段是整型的
4 e0 X8 s7 {1 @+ a. k4 O- db.users.find({age: {$type: 16}}); 0 U! a4 z/ W( m' S
复制代码 $ p3 d9 G5 X7 k/ h- m
对于字符字段,可以使用正则表达式
* v2 H* @( b/ X* ]* F) w- o查询以字母b或者B带头的所有记录 , Z. \& _5 W6 @4 R8 `' }1 ]) E
- db.users.find({name: /^b.*/i});
" i' v% y, m: P( ~% |5 _. Z
复制代码 0 k1 D: n: _( c: }2 [
$elemMatch(1.3.1及以上版本) ' j2 F* s/ `! p9 S. y D( c) G7 X
为数组的字段中匹配其中某个元素 " t6 O A: x' o, I2 Z B! h8 @- G
/ p2 S* D; C8 v7 C$ [
Javascript查询和$where查询 6 w7 y5 S( p1 f y6 b
查询 age > 18 的记录,以下查询都一样 . u4 E3 K2 n3 v9 S- [1 h
- db.users.find({age: {$gt: 18}}); & m0 b, J. {" S) j' N v. \
- db.users.find({$where: "this.age > 18"}); 9 u/ K. F9 Z. A! N
- db.users.find("this.age > 18"); 9 W8 e, g' a' x: G
- f = function() {return this.age > 18} db.users.find(f);
复制代码 : \ a8 o$ q$ h3 x2 w% v& ]
3 v! z7 ^: q, m" D% ^排序sort() M' |* V- r! u8 J, b6 L6 W
以年龄升序asc
* Q5 @3 e: ^ \1 s I- db.users.find().sort({age: 1}); 1 k6 `) j7 f0 c) O9 F
复制代码 1 \6 N0 O7 u9 A) e0 c$ \
以年龄降序desc . I" o. a: r( W8 ^4 Q+ Y
- db.users.find().sort({age: -1}); 7 W/ i% _& d1 @) {8 s8 X
复制代码
3 n6 U* ~/ N" Q限制返回记录数量limit()
( t8 {& b, L3 y. M返回5条记录 6 E! U Z( r, [7 p# I9 K
- db.users.find().limit(5); $ L& L c, G& I8 x* V
复制代码 ; o% _+ `( k5 d; ^0 l. v! {/ A
返回3条记录并打印信息
1 ?- H7 n( p2 j0 W0 v; C2 H- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
8 {. K5 s0 I; ?' Y
复制代码 ! B: B/ ~, P: z) ]+ P& g
结果 f7 O. ]2 U4 h8 M. X( A. h
- my age is 18 - `, H. ?* K1 w$ k3 X
- my age is 19 / j, J& K: t6 x: E$ v
- my age is 20
复制代码
- Q, a5 f; V$ H9 z9 H m( h. V1 a' X2 t: A" H P& p( {
限制返回记录的开始点skip()
4 E1 ]; N9 v& v" ~从第3条记录开始,返回5条记录(limit 3, 5)
- Z) y. h; m6 s3 B5 `& S- db.users.find().skip(3).limit(5);
/ {0 I5 D- R) W3 z$ p6 R; S
复制代码 7 K( [: h& v6 r; [
查询记录条数count()
& e: z' O1 d+ q' qdb.users.find().count(); " j5 [8 ~$ p' s1 X# U
db.users.find({age:18}).count(); . k/ r: i4 U! y2 ]7 q- Q4 Y2 Z
以下返回的不是5,而是user表中所有的记录数量
) O# F5 Q$ ~; ndb.users.find().skip(10).limit(5).count(); 4 g# Q, I: G, h+ W
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
. C* g# ?" F% F% k5 K6 ]; m- db.users.find().skip(10).limit(5).count(true);
复制代码
7 J/ A5 y9 k4 U, A1 N9 v
% d* Q& g! {) T) @0 d2 h分组group() O3 @! t! {* Q8 _" j
假设test表只有以下一条数据 + n6 O* P: H6 `# ]
- { domain: "www.mongodb.org"
; u; j4 s1 Y( C) n! ^ - , invoked_at: {d:"2009-11-03", t:"17:14:05"} 1 Z8 U' { y. i" G
- , response_time: 0.05 9 ?' G3 Z2 f8 a4 Q: J
- , http_action: "GET /display/DOCS/Aggregation" V- S. i$ `+ A% e) C( _4 J% ~& G
- }
复制代码
# e2 y" f) e0 L8 g$ s) E使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; ' u% H" h6 D, {1 O- }5 A' D# u' L: E
- db.test.group( " e/ ?; H0 A8 u& s1 B: D# B
- { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} d- P# I3 V/ c! f
- , key: {http_action: true}
; a/ r0 _9 U: b9 @7 V9 ^3 n - , initial: {count: 0, total_time:0}
- a( v" N( J* C5 X a9 E - , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time }
/ A( d1 v; S k! b - , finalize: function(out){ out.avg_time = out.total_time / out.count } ! [" Z# B2 c8 H' z
- } ); 9 n! ?; `$ l0 g! x/ p3 d3 X
# C7 O! {$ d3 j! ?) H3 {; [- [
- }. _% f0 x* m3 n# G3 ~/ A - { 9 `/ y7 H9 N% y- i) @" L
- "http_action" : "GET /display/DOCS/Aggregation", 7 f% A# B6 X3 V3 X, `2 d* ]
- "count" : 1,
# f9 y5 O, F, h! h. U) v- I - "total_time" : 0.05, " Q, z, z' c/ Z% T3 Y4 b
- "avg_time" : 0.05
( i0 T' I* F5 }1 a+ y0 ~ ^' D - }
% a( L9 i4 Q5 L3 o1 t# J% Q" N: { - ]
复制代码
/ c) [1 p! i7 q. e' K8 H$ q% I3 {2 F( s- d# |
8 [- G2 p( h& e3 k
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 和Min3 d( g+ ?: T5 e, w& j
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
- q: ]9 D' F( n# l* w. |! g
; m, v0 j2 {3 o2 T I- J. n* s; Z
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
0 v( h. f7 g$ g* |1 H% L# d* g; O. y/ l& S
他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
# A/ K. o; o8 a+ |* ]3 `+ x6 ?1 L5 L# U9 K2 Q' I- i) x# C; u* Z
我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码 % S# J! u9 h9 ^- j) e$ r
+ _$ I( m% l8 _
我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码 1 e x, t8 @& q+ O4 `! p- y+ Y
# u9 r/ g. ^! a1 D6 ^8 ? 输出如: -
( o0 E( ?: M% h3 P7 }+ ? - [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码 " r0 P) M$ B) S- L# Q
! i3 I4 Q4 m" P3 k( c( u/ c7 C: L9 ^: P6 {6 u( H7 ^5 m6 T8 J
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"* q9 P5 p5 y$ Y* U1 A
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
7 a X* N% F R! X6 p: B - xmlns:context="http://www.springframework.org/schema/context"; |( V$ V7 g0 l
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"
( U: M* o8 x5 H! X; M" w - xsi:schemaLocation="http://www.springframework.org/schema/beans) X% {8 f; r0 X( D9 T3 r
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd; F+ P, A4 @# u
- http://www.springframework.org/schema/context
8 A! ~6 f3 P' K4 ~4 R+ l; O - http://www.springframework.org/schema/context/spring-context-3.1.xsd
, \" s) ~: N5 A' i7 s8 k - http://www.springframework.org/schema/data/mongo
% K1 N- I; k" l/ z4 v2 b. T& ^ - http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"># j) S' R2 Y: A) o8 }8 I5 d; b
- / y6 W8 _, V( e+ {# I) u
- <context:property-placeholder location="classpath:mongo.properties" />1 ~- ?6 ]; I" P, [( y/ T
-
% _# F% o; |4 U7 d4 S8 C9 q - <!-- Default bean name is 'mongo' -->4 N( x- J) K' i, {3 }$ w" F
- <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />$ b( O* J/ A- X% p+ g) ^
-
" K) I* p, \/ y4 ]7 A- o - <mongo:db-factory id="mongoDbFactory"
, g) [7 u+ w' _. Y m) L - mongo-ref="mongo"
R0 U8 h; E* ]$ |# J1 S) a5 z - dbname="mongotest" />
: t# X1 y, J: t6 |1 u - 2 z& _* [: ^- t! S( A
- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
: D2 Z/ O9 ^) c# k7 J/ M - <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
# }+ j- z* w. ?6 R - </bean>
4 A0 Z' g" O: l, k. C3 ~ - </beans>
复制代码 8 S7 P* F* U+ l: l3 y1 p" t
' q& M# F& K$ i2 d9 v1 l* z max和min的测试: - @Test
8 ?( I; D0 w) G - public void testMaxAndMinAge() throws Exception {9 S9 A* K# L$ G/ C: X- v `9 J
- Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);5 d& r* \' Y! u- @, f$ H* }1 q
- Person result = mongoTemplate.findOne(q, Person.class);
" N% I' C7 b" i; p - log.info(result);5 B* g0 v! p5 u. G& @' f$ _+ }
-
) m5 y% ` b3 q `! p1 Q - q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
! m% m8 d" y* b+ O' @ - result = mongoTemplate.findOne(q, Person.class);
8 H9 L5 _* ^/ O- {( ~9 R* c - log.info(result);0 X5 v/ r8 x6 }! n6 t
- }
复制代码 7 Z; d% S, T$ j6 ], R2 c
. A9 u3 c& x$ Y distinct的测试: - @Test
, ^2 T; i8 f; I" o& J, w- i0 z7 {, Y - public void testDistinct() throws Exception {, y+ [9 \+ N/ y* I
- List result = mongoTemplate.getCollection("person").distinct("myFriends");( Z2 k2 P, m: s" A9 Z
- for (Object o : result) {
" |* M) M/ u9 s W, N+ ` - log.info(o);
; X% [) f+ B" M8 ^4 Q - }
6 t$ z1 S* z9 D0 Y- ? `+ j - ; r3 {2 g, w+ T& m7 t: M
- log.info("==================================================================");5 }9 m9 w, O& l% v2 w
- Query query = Query.query(Criteria.where("manId").is("123456"));2 I3 H' E' R9 [2 p
- result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());% f$ k" p- C" S; w; k9 z
- for (Object o : result) {6 l% P- M5 r# p7 ]
- log.info(o);
; s' ] w. K6 }! {" f6 u. U; H - }
% u/ k8 l, C3 Z -
# r0 J9 P, ^/ F, b - log.info("==================================================================");; V/ c0 w( T. X. ]# N
- result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
6 @! B; K) [2 [ - for (Object o : result) {
; o0 l9 u5 k! h" L- w0 d - log.info(o);
7 z" X$ N" _' K! y8 }9 ? - }
" v+ w( U3 I* D& P- q. R E - }
复制代码 6 }0 {% A, p- J* b
: c2 L( M+ e8 M8 | 输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 2345679 x. b! F, B) W6 E3 ^
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 3456785 k3 f E. z% Q
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789
0 L( S9 o% c) D% _- ]) C - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654+ c5 I$ j8 H& B8 b
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni; Z. J9 I% J# v7 e
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo- f$ O: k- L% i3 b( f# F
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
! G, f' N: D, H y - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================+ D/ o, g6 H5 y; C# ]& E3 b
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567; v) `. p8 N" J: Q
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
: B4 f& l% N2 t2 a+ ?5 h5 m - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789: ]! @0 ~7 l( D& c1 T* T' C( i
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
) E9 l0 f9 Y' l; M$ Q) o. i( _ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
5 L; T& ?3 H) x1 n# ^9 @ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
1 k3 [) \5 h% e2 P6 u - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb* I8 ^2 d* s( b
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc' D0 }+ h) h# U
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
, E6 s* j5 m3 H- x - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
2 |5 R% |6 V) v4 F* J - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy, |4 N% r1 ~0 G
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
& _0 B q! G+ S& Q( F - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
) h% o7 ^3 C3 k/ D) E3 m$ G - 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
复制代码
* H( H& z2 f# F2 F2 B
$ U% S- t/ m5 E$ v5 p% w3 l$ R 这里我要特别说明一下, 当使用了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等信息。 % Z$ d) F5 E3 F3 o
6 N b; o: h/ P9 p7 d4 b& W1 g
/ M+ j/ D k* V5 B- U" w |