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