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