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