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