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