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