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