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