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