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