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