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