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