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