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