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