版本一:
) E7 }: _5 S" }8 n. f. I
; J; w" [5 Y4 n/ d0 n1 ) . 大于,小于,大于或等于,小于或等于3 L& I) t$ p5 q y4 z
8 Z6 l9 a6 w0 ~" ]! _+ g% n! V$gt:大于
; O" N7 v. S5 Z6 ]3 X$lt:小于
+ b! y: @9 b- b! ^$gte:大于或等于3 v8 y. r1 f2 ?6 g- i# P5 b
$lte:小于或等于) O1 v7 X1 \1 C9 r
* n* y" g# t3 E5 c$ I例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value
/ z+ G9 N9 g, Y - db.collection.find({ "field" : { $lt: value } } ); // less than : field < value* o8 K7 z: y4 m7 |7 ]
- db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value6 i! W- {/ P2 l2 g: _& }
- db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码
2 |7 S6 L) W" B如查询j大于3,小于4: - db.things.find({j : {$lt: 3}});
9 D& _/ P# A+ ]( [: [ - db.things.find({j : {$gte: 4}});
复制代码 , [) l( P8 L% ]6 h+ t+ k
也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码 $ Z+ [/ g! Z r7 u
. t# v. |, B/ J# ~& A: H( ~
4 d$ Q6 V7 S& _' w6 w, ]7 |9 R2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码 ! I8 B* t5 j; w* N
3) in 和 not in ($in $nin)( W: }; }! N; D8 i! w
1 a- x5 O/ P8 `8 N; c) Z: d# }语法: - db.collection.find( { "field" : { $in : array } } );
复制代码 6 b+ I' F/ S, {2 ?3 w
例子: - db.things.find({j:{$in: [2,4,6]}});
5 ] J$ G$ W2 T% N3 Y% M4 }# o9 m - db.things.find({j:{$nin: [2,4,6]}});
复制代码 & g' \! u: X: m+ l3 h
+ T- P/ M5 g9 J ^0 d$ s! s+ J0 N
4) 取模运算$mod7 ^* n1 G# F1 I3 x& D9 n
( k d4 K2 e, v2 L7 _- t; n如下面的运算: - db.things.find( "this.a % 10 == 1")
复制代码
# C+ w; G* s+ f4 W可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
! ?/ L2 m0 }6 e4 c) m3 c' h# C1 V( A" k# @" N& {4 U8 Y/ K
5) $all
v: Z: E! j; F' _ Q+ W- Q8 V9 z' | g3 {- [! L+ E, W$ Z
$all和$in类似,但是他需要匹配条件内所有的值:7 M. D0 N u; c- I; k
' C: c" n3 z9 ~. o5 p, w# J! Q
如有一个对象:5 J3 p2 X7 W' z0 W( c
: J% F5 s' w0 E1 E& V
下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码 0 ^9 A7 q5 E p c4 D1 |& Y
但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
( ~( }4 h& g& n$ ?/ t8 a
1 m7 R% T' ~6 R# C6) $size
, Z2 H- m+ b: Z
; @2 ^' r4 _# t- s. _8 A" j$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
' S: ~8 q2 u/ p- {' J+ Z# R& d& L3 Q3 B. `" s5 h
下面的语句就可以匹配:
- db.things.find( { a : { $size: 1 } } );
复制代码 5 L4 x( ^1 s! A! p H b0 F( G
官网上说不能用来匹配一个范围内的元素,如果想找$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 ]+ u$ g8 N# F# M" j
7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回8 w. n, S1 ^3 r9 o, b
- db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码 4 m9 f" ~ f& k( I2 L' ~% s# a
8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string
( a' n- K( A$ k6 M4 a$ M( @ - db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码 . J7 u: h8 C7 c9 W9 y* {9 r
9)正则表达式& N7 w5 _* a9 N: V2 `3 a+ F
: A0 e/ s _8 H( amongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
/ Y% ~& ]' P6 i3 W$ i10) 查询数据内的值
: t3 |1 c/ X4 @- y/ ]% Z5 l. \9 s/ G( S+ v5 Z9 I- J
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码 9 F% h- l- F; `( ?
11) $elemMatch- }6 o( U; f' z9 J3 u2 n' p E
3 t: b6 b+ \& [) S& A& Q如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
, }( M8 f0 z3 G a2 H) { A' M - { "_id" : ObjectId("4b5783300334000000000aa9"), $ m' w0 F% Y+ h$ K9 F
- "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
! j( y+ }1 A( b# Q, h0 J - }
复制代码 ! |/ h! k: K- E! o3 d1 H0 o
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
8 v) A; B7 c1 f g$ s$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } e/ Y" H! o+ G* y% c: D
( s9 o1 |0 a2 O V& J1 o( Y12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码 " T7 Y* m0 E- s; }9 G
举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
, M% J, i8 ?3 Y如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码
+ H0 d- o) D r) H1 N- R如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
1 I- o4 O5 a: d! c下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码 . W+ C5 K+ ]( y% l8 p
是不能匹配的,因为mongodb对于子对象,他是精确匹配。
6 Q$ c5 P) H4 W, D" N/ q) D4 p13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );6 q9 i" O% {# S, ^6 q( r
- db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码 + h) _* B2 R: |* w# C9 _
shell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin
6 _5 j) U2 r9 N4 a5 C
1 }+ F* f# X: \% N% T. I, ^ 2. #增加或修改用户密码
$ b& z; v7 \8 e" B8 z# Q; n4 W+ G# X 3. #查看用户列表 4. #用户认证
7 L# D$ w" x8 J m6 I; G6 x 5. #删除用户 6. #查看所有用户 7. #查看所有数据库 8. #查看所有的collection 9. #查看各collection的状态 - db.printCollectionStats()
复制代码 9 ]6 x/ k+ |" r3 o. i9 m5 h
10. #查看主从复制状态 - db.printReplicationInfo()
复制代码 0 S- j5 l& u/ K/ J# W2 H
11. #修复数据库 12. #设置记录profiling,0=off 1=slow 2=all 13. #查看profiling 14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码
! U2 }5 E: i# w P6 K: P$ Y. Q& k& { 15. #删除collection 16. #删除当前的数据库 6 C p: p3 B0 E/ D: q) B4 V! F
2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码 9 P2 ]! L, i: U+ H3 d
2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
* F3 C0 B! V4 P& q0 ]! b6 G 3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码 3 K x3 u; k e( A
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()
. A( r+ j/ {: T" J( ]; x' K6. 高级查询 条件操作符 " _# E# A* e/ n# f+ s
- $gt : > 9 m+ Z5 a" |* Z0 @+ _& ^3 A* B z
- $lt : < 3 w2 O4 ~) K$ X% A+ A& J
- $gte: >= & v) {$ K. o$ c% L9 N0 b2 ?$ K0 @
- $lte: <= , d, h; _( {. w- s* A2 @
- $ne : !=、<>
: a2 z) ^* B: s - $in : in
4 d' x6 n: i4 g- r7 s9 j$ y" G+ U - $nin: not in
. [" x% d9 H( t7 s$ D* `; W - $all: all 7 }! J1 w# L7 p( s# Q
- $not: 反匹配(1.3.3及以上版本)
复制代码 4 _; @1 g9 W% Z+ P' k X
$ p1 \: U. _, @8 c+ P' T9 s, I查询 name <> "bruce" and age >= 18 的数据
0 {, |) o' D8 b: K- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
0 Z' j' j$ e- p4 t/ A+ h# Z, W
, K$ w' O# ?, }. d% l查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据 % X% U4 T. X0 T
- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码 & t4 J {& ~) o4 q" p1 l: O
: N8 l+ X+ S" {( W) n* @5 k
查询 age in (20,22,24,26) 的数据
6 g& N; g8 d7 z. T+ w- db.users.find({age: {$in: [20,22,24,26]}});
复制代码
: f+ {, T9 ^ m7 ]+ R# n+ O* k6 u1 w- _* M
查询 age取模10等于0 的数据
0 E( m$ D( _3 o! O$ m- db.users.find('this.age % 10 == 0');
复制代码 ) c6 m9 e/ q2 i' A) a. y
或者
/ F5 t3 d. U9 w2 K' q) N- db.users.find({age : {$mod : [10, 0]}});
复制代码
+ N% S* z' v! B, o: o, r3 X4 G3 \- b7 J# r9 i( }. w
匹配所有 0 b& x- e0 |( X# D
- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码 + ~9 V+ @: n+ C' }" j5 i, _
可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } . E5 {6 B, }/ x0 |' u7 j( E+ G
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] } + r+ }, e# ~) B( {
" ~1 c! ?" S) z7 E m) m查询不匹配name=B*带头的记录 " l6 e& z0 m9 Z
- db.users.find({name: {$not: /^B.*/}});
复制代码 & z% {2 U; [7 l% L3 h
查询 age取模10不等于0 的数据
% Y {( ]; g5 G0 I5 e! i- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
' X% g D7 q% [, r4 B+ w2 s z
$ h, ^" U; P/ n/ j9 e0 J B/ _+ u#返回部分字段
Y, o. H1 i. _$ K7 C1 X选择返回age和_id字段(_id字段总是会被返回) , r4 Q2 h. R# w$ l1 T+ i3 i
- db.users.find({}, {age:1}); + n( ~/ O7 j& m% I( J7 M
- db.users.find({}, {age:3});
4 L- R, N3 l( F4 O - db.users.find({}, {age:true}); ) H% y& b6 y5 Y
- db.users.find({ name : "bruce" }, {age:1});
复制代码
, ^( a1 v0 O% o( A) K& d2 f0为false, 非0为true 9 c9 @' ?* a! R; u c0 M
" F# c7 Z0 G3 P6 W& e选择返回age、address和_id字段
- A, S3 }! D! y2 V- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
: b' t/ i. b5 h `6 J l, s! H; ]3 q
排除返回age、address和_id字段
( _( z1 y# J) j( t- db.users.find({}, {age:0, address:false});
: |/ f x. z. m ?! T - db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
0 C7 n. }1 Z* q: j
+ l9 F7 O+ P' s, N6 B% c数组元素个数判断 5 J* v3 o! A+ _, I/ a5 P1 }) o
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录
) U; p& d1 t; A' S匹配db.users.find({favorite_number: {$size: 3}}); 6 W- Z0 o b4 z; M" Y
不匹配db.users.find({favorite_number: {$size: 2}});
/ R( Z! P8 |& g2 F5 t: ~* Q: Q& \ P) f( s' j0 O
$exists判断字段是否存在 3 ^3 e, a' M" M( [5 n% |7 B
查询所有存在name字段的记录
5 y! C4 Y) `+ N- db.users.find({name: {$exists: true}});
复制代码
2 C( O: S: D& g) [5 S查询所有不存在phone字段的记录 ' a$ c8 F9 R& l+ k; V- d5 j
- db.users.find({phone: {$exists: false}});
复制代码
/ L" P9 ]& r$ G% N" ^9 R ^' q: `' }, v! s4 e- x9 @
$type判断字段类型
x! q, n. a Z! o& H查询所有name字段是字符类型的
" T4 \0 p) ~& ^" J- db.users.find({name: {$type: 2}}); 8 D( s( P% c8 N( F5 b$ a
复制代码 ) v3 W+ W. o% m7 B, H/ @; y% K' C
查询所有age字段是整型的
: S( I1 D+ a0 N( ]; u9 D7 y1 e- db.users.find({age: {$type: 16}}); . ^- \0 F2 h$ [- o; O* Z
复制代码
2 X7 v I: i. _* w! H& q7 k% {$ R& X对于字符字段,可以使用正则表达式 5 a' U" u/ _. T# q
查询以字母b或者B带头的所有记录
1 }6 O( |3 z* @/ H( N1 q$ ^- db.users.find({name: /^b.*/i});
: B0 Q7 J" F+ o$ @- P
复制代码
/ c1 o$ a* M- f, x$elemMatch(1.3.1及以上版本) 2 |+ H/ @0 o1 U! [5 ] v1 ^" U
为数组的字段中匹配其中某个元素 / a. U. A5 o. Q M/ k
" l( J0 \2 j% I- S' G, O% }Javascript查询和$where查询 $ A) _# G- @1 n" {& ]% o! Y$ R
查询 age > 18 的记录,以下查询都一样 3 R$ V: T: V3 f+ G! e3 V
- db.users.find({age: {$gt: 18}});
" ]$ H4 D, U ~1 T) |' i" [/ R - db.users.find({$where: "this.age > 18"}); % ]9 C5 @0 O1 M8 H
- db.users.find("this.age > 18");
- l+ B) L0 z/ A. v+ N( w+ ^ - f = function() {return this.age > 18} db.users.find(f);
复制代码 0 S6 N( y: w& l" |- u
9 N8 I. T# M6 Q* A# B2 ^5 S排序sort()
7 k8 ?8 W" E: C* I) Q' X2 Q以年龄升序asc 3 ^8 m% K' _* {
- db.users.find().sort({age: 1});
: ?6 ?( w- P1 o, y
复制代码 1 a; x- ]; e* r2 |
以年龄降序desc & N# p" ~2 }; }( X4 X. U4 C6 a
- db.users.find().sort({age: -1}); " B j, R2 T+ C* r
复制代码 : h2 M2 A# L- W* a$ o7 I
限制返回记录数量limit() 3 _9 u- H/ ]! `2 ?) g3 i
返回5条记录
& W; d0 b$ T. d2 J' |- db.users.find().limit(5);
# q$ |1 I# n2 _, m8 |' }/ p7 p2 J
复制代码
/ B( K4 v$ z9 u' U+ c0 B返回3条记录并打印信息
! |! Q9 @3 s: w) p, w- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
% ?+ [, p4 T+ a; E, C
复制代码 6 ~; }2 I- O& t s% c9 ]8 T6 O) K" g
结果
, _ U( e' e+ x; P* t. w. d8 w- my age is 18
" {: A% \: C: T5 A# D" b - my age is 19 ! x9 k# ?: l: W, {& y7 C
- my age is 20
复制代码 4 _9 h q# u a! @+ t
; \9 b2 Q2 J, p. R4 D
限制返回记录的开始点skip() ! e9 ]# }3 s M6 X/ S& |+ W- i
从第3条记录开始,返回5条记录(limit 3, 5)
4 r4 T3 d0 b# I4 L! i- db.users.find().skip(3).limit(5);
, @- t$ n; K0 @3 y5 k
复制代码
# X$ h# [5 Y0 L3 i3 r2 X9 L查询记录条数count()
" W2 I# l3 V$ C C4 Ddb.users.find().count(); - u3 g1 R0 X4 U" E' ]7 | V
db.users.find({age:18}).count();
" |- H8 W/ n O( N9 f' d以下返回的不是5,而是user表中所有的记录数量
; L: O5 T. {' x* B8 u2 vdb.users.find().skip(10).limit(5).count();
. o/ |9 F8 M. ^+ a如果要返回限制之后的记录数量,要使用count(true)或者count(非0) 5 Y: G1 b9 h0 u1 \
- db.users.find().skip(10).limit(5).count(true);
复制代码
) \* M' R6 y# C# e" `% J3 v# K7 ~. `$ w$ T, n$ I+ R$ p) H
分组group() & e( Q4 O/ S+ n% o3 O
假设test表只有以下一条数据
* W' M2 O5 A$ u- { domain: "www.mongodb.org"
6 ^4 K8 E4 d- h, ]+ G - , invoked_at: {d:"2009-11-03", t:"17:14:05"}
9 u% Y0 A p, r$ ~1 E5 H6 F - , response_time: 0.05 5 z3 i7 _' C; u# `/ X/ [ O
- , http_action: "GET /display/DOCS/Aggregation"
9 I9 D9 ]1 b% Y8 S - }
复制代码
5 G4 j8 ~% g2 ]) G) z- f, m% B8 M使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; ( V9 B6 L3 |' L1 G
- db.test.group(
Z% @$ x: z- d0 c - { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}} 0 K8 J6 Z* E2 V$ @
- , key: {http_action: true}
/ ?6 E- S+ X4 `3 m, y* l9 G8 C - , initial: {count: 0, total_time:0}
8 @7 I. R9 |2 K g - , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } + P _7 m( E% G% c' |
- , finalize: function(out){ out.avg_time = out.total_time / out.count }
- L% U- W c. w: B2 L - } ); " ~' ^, d: b: h- Z5 K. S
- 6 ~7 V7 e( R; I4 q+ Y$ X A
- [
5 k5 O: t% |. D6 v - {
2 B/ e1 x9 q* K: u2 O" N8 L - "http_action" : "GET /display/DOCS/Aggregation", % d7 C1 h& v0 K# k' ~0 L: X9 O; r$ J
- "count" : 1,
2 P# J& {3 P* y! P ]6 O& x( l - "total_time" : 0.05,
. m! q3 K. P$ h; U: _ - "avg_time" : 0.05 + s+ O5 n# g, _( K& z Z! A! C
- }
/ i1 Q% }/ O0 Q% J3 m7 h( u - ]
复制代码
" A. u9 g: S5 s2 ^6 O! e$ p$ V- v
4 o9 `- b. D% {# n* Q- m: j5 ~% Z/ d
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
; d' W" e- q+ W3 C! o
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
3 q5 C& ^, x! n. Z! v( T# ~; |% o8 v* R. ^& k" N2 R ^" }
) n/ m9 |# k9 Y ]
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 - distinct% p/ l% [* S3 Z! e
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码 , J0 `, i% |2 m. H. N9 c, [* U
: W2 }( r% L, K, i0 ?3 s( { 他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码
) T; U; q& u6 r+ T
! G$ [7 B9 ^% C" W8 Y N" D 我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码 ! |) f' e! e8 r1 ?9 f5 W
4 n3 N# h# [. p# o* H 我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码 6 T8 I' G o. F* [0 }
- y" q( ^- r+ R9 R5 X
输出如: - # i3 T* c4 Z. m* i
- [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码
+ a' K" m' k4 h: V7 }7 P5 T* t$ n7 c+ U! i: {( D: U# |* E! r
* s6 ~, N8 g% k那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"
& b. y! G- h: M- X - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; Q/ V# P2 K4 L2 J3 _, E0 x" E0 F
- xmlns:context="http://www.springframework.org/schema/context"
6 C0 Q. }. g9 C - xmlns:mongo="http://www.springframework.org/schema/data/mongo"
j1 Y: a' w; ?# Z2 A0 K7 f - xsi:schemaLocation="http://www.springframework.org/schema/beans& Q: ?, W5 W, m r& r
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
|1 A6 U! x! X9 C - http://www.springframework.org/schema/context6 Z# d8 q! Z6 ^
- http://www.springframework.org/schema/context/spring-context-3.1.xsd+ I) j$ a6 c1 ^6 F
- http://www.springframework.org/schema/data/mongo
! @' L/ `& c Z8 _ _2 N. ?) R - http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
7 ~; `5 v8 t6 u! B/ l" i: H. y -
6 ~% T p; O: S; }* L7 c - <context:property-placeholder location="classpath:mongo.properties" />1 n: w. | i5 Y8 W: q1 |+ _
-
) p: M* q* q" M; [ q8 z* g - <!-- Default bean name is 'mongo' -->* b* Z `2 `4 |3 r: Q" h
- <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />+ ~/ V# K: H) u: U4 g$ s$ I2 [
-
: F' Z) j0 G' M* Q/ t; P, G% u - <mongo:db-factory id="mongoDbFactory"
4 W7 h! X/ e; ^+ K5 e0 e5 q e4 | - mongo-ref="mongo"/ t" ~7 X6 Q! w. B' o2 G: P
- dbname="mongotest" />
! J2 F8 e" g; g' f: F+ ^1 f -
% W: ^. S8 u' h& e* `5 p - <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
) ^. ?! I) ^# a! W/ [; g - <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>* v1 P. T# k) o) [. w4 K
- </bean>' P! C6 c4 X! F
- </beans>
复制代码
: ^) W2 x& ]# b$ o4 E7 ? : ^ s [2 K3 b4 A, x5 U8 S' K
max和min的测试: - @Test' t% H) g x+ [7 K
- public void testMaxAndMinAge() throws Exception {
( u4 F" i3 B/ Z1 | - Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);7 w) r- H5 n! }- j) B2 J& J# Z
- Person result = mongoTemplate.findOne(q, Person.class);3 l# z! C/ m4 H* x' |( j
- log.info(result);. ~/ C, t v3 ~( Q7 i5 T
-
$ i$ x0 D' E0 t9 V( Y7 p - q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);
3 B+ w0 l1 _2 N% H2 d; _/ Q: s ` - result = mongoTemplate.findOne(q, Person.class);, Q, m/ f6 v- H3 p, s
- log.info(result);- J2 s( b( y" X1 N
- }
复制代码
* m9 a% l# B7 w0 b1 l2 Y4 ` A# u2 h$ {8 [
distinct的测试: - @Test
0 ^1 N: x$ R F8 G8 Z - public void testDistinct() throws Exception {4 @9 C: U4 s( v2 {
- List result = mongoTemplate.getCollection("person").distinct("myFriends");8 j7 R2 A+ M4 H9 z( Q8 |2 N/ g
- for (Object o : result) {
1 ?! B; D! \. q* l, R2 t - log.info(o);
( j* I+ ]0 l0 g: o - }2 _. @3 k5 N3 c7 ^9 v/ u0 u& r6 d9 T
- 9 Q' Q7 p' V% [) O
- log.info("==================================================================");. `& D- n* K! n
- Query query = Query.query(Criteria.where("manId").is("123456"));
; V4 i3 F. M. d5 m/ U' L S; R - result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());( w, ]( G/ @' H K4 p
- for (Object o : result) {
- X$ Z# N* ]9 f% \- L - log.info(o);# u' R& I: A0 T4 M
- }
/ f9 n# K" R+ y Z8 w& j - # X& J( [, E2 m6 M2 Z
- log.info("==================================================================");
7 e5 Q- e. @0 M* A0 X- R - result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
; w! N' A+ {4 @6 u1 D9 J0 X - for (Object o : result) {, o, W: Y9 A1 L x
- log.info(o);1 T( |. q x2 _0 a0 t/ }
- }
2 Y& G/ z x6 f- y; N0 I1 @" K8 ~ - }
复制代码
; ~" H; r# r7 Q7 |! k
- O$ Y6 T6 r* a- W3 W 输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
. \+ u% o. I$ \. C: L4 v: @ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678
; w7 g! y% m# x - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789& B1 w, b$ c- R& u( R, q
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
$ X8 G( o6 V& z - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni7 C# o) \, |8 j4 K3 Q) r) g
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
" ^( q* D$ M6 H: _* a Y" L9 G, f - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
1 v6 C! V( ?8 r6 D/ @' A" X+ d7 u - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================' K" q# V6 z" |: H* \: o3 w
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
- O% Z+ l X, g& i/ @# V, Z - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678
/ C/ T0 s/ F' w1 j6 \" @% Z - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
6 M9 V0 a# N* X% B! ?( u/ x* D - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 987654
( v# ?4 T# E: R5 A/ n. a& K - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
: [) \) M7 o, V9 v - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa
! c, @, F, P. c5 h. o$ G; ` - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb- _, [7 U; p/ j1 f
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc
" O6 L7 J2 J$ f6 b) Z: Q - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
i1 ?5 z/ r7 d5 a - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
- v; _/ N9 @! f - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy2 \3 Y2 z; @8 E% E5 N3 I2 I
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
, C3 z4 C! W7 I/ e# j, Z/ C( Z - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
* ~* K% F, q( ^! f; s - 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
复制代码 , m3 k( p3 U$ E% z! p7 ~/ v
# z& h7 m2 F- q( ^
这里我要特别说明一下, 当使用了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等信息。
$ I( H- c% T4 ^5 U2 z% U" `9 u# r
; }7 A/ i8 W5 r- e+ F |