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