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