|
版本一:
+ _# i4 F2 O8 R7 p B
: l B6 i1 X2 F- o2 r1 ) . 大于,小于,大于或等于,小于或等于$ G; D5 A6 w, p. A
z1 G+ Z' F- M/ N# g+ k% {* R- O$gt:大于
$ u" I: \7 y; p4 n0 W. x! H$lt:小于7 ]( K( h# s5 V, N' Z+ u# \
$gte:大于或等于
1 F) }& a& ?7 [5 y/ R8 j, |+ \4 w$ P1 u$lte:小于或等于* z7 ?" C6 A! U( B' G, R9 H
; U# t" Z; d/ |9 F% E! l$ A例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value& d- n1 z0 L* j6 X! G0 k" D' o
- db.collection.find({ "field" : { $lt: value } } ); // less than : field < value
! b, m1 W1 b4 s - db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value0 x0 a# A1 R0 L, n
- db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码 * V; y3 [8 p0 _; b. U
如查询j大于3,小于4: - db.things.find({j : {$lt: 3}});) H* D: v ]+ B& g) Z: x Z
- db.things.find({j : {$gte: 4}});
复制代码 7 U6 c% @7 @4 c
也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码 1 ^, }; C6 \4 i
* L& \& Q$ G* i
( y3 q3 f) ~( D' i! K2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码
% x1 |& e" b" Z0 `% L ]- Y3) in 和 not in ($in $nin) S% g. Z8 U1 {! `8 D
0 m* Y& u; c6 w D7 X语法: - db.collection.find( { "field" : { $in : array } } );
复制代码 ' `: z5 p5 N1 T6 L# u5 h6 A
例子: - db.things.find({j:{$in: [2,4,6]}});
* @ r7 [: M' a - db.things.find({j:{$nin: [2,4,6]}});
复制代码 * x5 s" V/ [- @' `" f
; v% H8 Z* N6 q9 j7 p$ H
4) 取模运算$mod0 g2 F, o4 w M7 q! P9 ]" ^6 k
# L# N I2 z2 ]( }+ F
如下面的运算: - db.things.find( "this.a % 10 == 1")
复制代码 0 D3 B; s* L5 G- V/ T$ e
可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
8 w* w, s* r7 k7 A
+ s' ^* n K) A" z/ D5) $all+ T: q3 b. I4 u2 U- ?' Z j3 U
S* ?( A# L4 V: Q! {! p
$all和$in类似,但是他需要匹配条件内所有的值:: {% g# C0 m$ S
- M% C9 M. V8 e4 @- Z9 E如有一个对象:- _; q! ~9 w+ Y( }# i+ K+ ?
8 t1 n( G; ^3 r; ]下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码 , T2 d: |. L" e, g3 T: d, A
但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
* K( N6 K) T) O' _* M, \
4 p( D @7 L; c4 z& R6) $size: l# B) }6 L! C4 o
% @* N- @* {' B6 {: Y$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:/ o( p& @ F( j9 B! T, A, A: L
) _4 `) {6 X$ Y1 {0 ~下面的语句就可以匹配:
- db.things.find( { a : { $size: 1 } } );
复制代码
( ]/ G$ H5 i0 U% h8 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. , q7 J3 M0 y$ P% ]9 q, d6 y
7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回% q+ Q# J8 a& v( B( z1 D; U
- db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码
{% d3 ~7 X; i! z9 @8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string( E- L7 s* ]+ Z$ a. c, z: {. @
- db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
$ j( n4 p) N/ F9)正则表达式' ^4 Q X4 `6 J$ K& k5 u0 q
; K! q( }1 X. R$ R- Ymongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码 3 S' U% V# W/ i) K& c9 d
10) 查询数据内的值
5 Q4 `* K: L7 G- ^( i4 @: |2 F* {2 z% u$ v2 Z2 `
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码 4 d+ o9 {' o* S, q
11) $elemMatch; I' q1 q% B3 S! n) B$ U
' ^: M! _' d! u4 l4 L
如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } )
$ H6 D& J; t1 ?1 x - { "_id" : ObjectId("4b5783300334000000000aa9"),
$ V0 G. t' z, U" U$ U - "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
( [0 n( E) v4 V0 V# ^% p. P - }
复制代码 : ]) n6 \2 P- F; y, T* J+ p% S
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )
: R. D2 ^0 L8 }$ }3 |$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }
% M! n# e$ `8 \8 A. i. [4 ^: h, n2 T! t, F4 F4 c, m W* c) k
12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码 . u3 ?: u9 @5 t3 J1 ~ J3 [
举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
: K- P' x% ]2 T+ O1 v. i如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码
* g) ]7 ]1 k; _如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码 6 f/ S [6 h4 R- N
下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码 ) D: N# |% ]2 ?# S
是不能匹配的,因为mongodb对于子对象,他是精确匹配。 $ t: t+ F4 _" [$ J* m
13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );! |9 m; D; |5 [8 R& J
- db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码 , x! z4 s1 p0 P/ O7 N+ i9 X/ c
shell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin 0 q# M- a `5 B! D
. V4 @1 y( N j
2. #增加或修改用户密码 3. #查看用户列表 4. #用户认证
' O) |( ^! A* l/ d2 V! }, d9 v 5. #删除用户 6. #查看所有用户 7. #查看所有数据库 8. #查看所有的collection 9. #查看各collection的状态 - db.printCollectionStats()
复制代码 8 d0 t2 E {1 B
10. #查看主从复制状态 - db.printReplicationInfo()
复制代码
. {9 M; I, v3 y 11. #修复数据库 12. #设置记录profiling,0=off 1=slow 2=all 6 E7 y1 I( a' g% n5 \8 s) A
13. #查看profiling 14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码 9 W' i+ Y, a+ f1 f8 Q; s1 K( O
15. #删除collection 16. #删除当前的数据库 2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码
$ n) W3 u$ H1 R 2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
( S( E, c& [+ } U 3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码
9 I+ ~- _. x$ F5 k3 k5 |! E 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() 2 q/ R E% I( |4 {1 n' k
6. 高级查询 条件操作符
, G0 [; u/ G D9 a# Q- $gt : >
' t) z$ s3 j0 ` - $lt : <
; D0 p# b+ s/ ~8 v% b! L0 h - $gte: >=
1 E: m$ U, O0 r0 Y& Y - $lte: <=
& _: M9 s3 v9 ~8 a, V" j - $ne : !=、<>
: M% b) R' }* u0 ^( K - $in : in
3 P( Z* q7 S0 @$ j8 d! X - $nin: not in
9 z( h2 j% o0 ~# L- N k6 H - $all: all $ F& r! T4 V5 B6 `! p
- $not: 反匹配(1.3.3及以上版本)
复制代码
, o% p2 W9 {2 w0 d8 J: N8 ?) O2 a. d( F$ u* L h0 a9 e) {
查询 name <> "bruce" and age >= 18 的数据
6 H) X0 ~; M) f5 q9 F# J U- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码 9 D% z l! X- G! C
% P1 E6 N9 @0 z$ c$ q查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
) U4 @9 w6 o; r6 ` e% W9 L- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码 ( S7 M; R) i m* s R
5 j0 J; M0 T& o5 s查询 age in (20,22,24,26) 的数据 5 ~9 a. t% P5 [, a/ R4 `9 o7 t
- db.users.find({age: {$in: [20,22,24,26]}});
复制代码 , b: ~0 o7 ?4 }+ d( n8 X/ a
2 i/ d2 W4 ]/ J' s! E8 j
查询 age取模10等于0 的数据
! T9 ?( b+ b) V- db.users.find('this.age % 10 == 0');
复制代码
! X1 `1 K+ G! n或者
7 R7 z3 d) a% Z- db.users.find({age : {$mod : [10, 0]}});
复制代码
0 W8 Y% G; W/ G8 \# A1 \3 d/ z2 u, _6 Q6 D$ N) V& r
匹配所有 3 z( Z1 e/ ]& x, I l, |7 |
- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
- K$ }" a. D$ K; g可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] }
$ M. ?) t7 E1 J! G+ k可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
3 R2 S+ X4 T' K& i6 c7 @# _) p
- c8 ]5 s0 G2 g- a- i查询不匹配name=B*带头的记录 1 U- ^2 y& G, I7 O' K
- db.users.find({name: {$not: /^B.*/}});
复制代码
+ I1 E6 f# F' ~2 i. v$ L' r9 f查询 age取模10不等于0 的数据
4 B- W/ S" B1 M4 u! f1 I$ r- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码
4 g7 ^+ X) a7 j3 k- V
& ?0 e o" M9 R#返回部分字段 . k4 O/ f' L1 o% o! D8 t
选择返回age和_id字段(_id字段总是会被返回)
. ?9 ~6 A) H: A1 D- db.users.find({}, {age:1}); ! W9 q1 T2 g8 V" f% ^- K
- db.users.find({}, {age:3}); 5 A- U% T. k8 t4 ^
- db.users.find({}, {age:true}); & {/ z: e$ T( |" Y: B
- db.users.find({ name : "bruce" }, {age:1});
复制代码
9 ]( A7 m" X9 g4 Q. b- C0为false, 非0为true , j$ u5 T, E0 B% {
# f$ c% b9 e3 r' O( z( f; l4 f
选择返回age、address和_id字段
% C3 g: ?) e* j' z- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
) k+ S7 G7 ?. ?: u3 l. D
1 y9 K! E9 K+ F; w9 f' [3 G. F排除返回age、address和_id字段 - q7 B) X# a; a" w
- db.users.find({}, {age:0, address:false});
0 B; }& z! ^5 Q' _# T - db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码 1 d0 L1 g) J& P6 f; ]( `- d* l
2 P. U' q% H" K+ w O数组元素个数判断 $ ^; U4 ^( S T6 p
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 7 r6 r! w/ i' h% F+ g1 Q
匹配db.users.find({favorite_number: {$size: 3}}); o* L; o$ y& g) i, k5 O
不匹配db.users.find({favorite_number: {$size: 2}});
1 s O* s3 w5 ]3 c. i4 W
6 v3 `) v: X) Q) E& ~3 i$exists判断字段是否存在
! i G5 c" T- | _5 K2 O查询所有存在name字段的记录
, y( n. g( G, T, ?. X7 ]- db.users.find({name: {$exists: true}});
复制代码
4 D' s( n4 n) W. z) [$ X- m查询所有不存在phone字段的记录 6 G) }2 M: P1 F4 {2 b( r: T
- db.users.find({phone: {$exists: false}});
复制代码 8 K; w8 H& C) I, C
7 K# N4 h" i, t6 i
$type判断字段类型
8 A( C# w7 X; c查询所有name字段是字符类型的 3 @; R. S" @7 ^9 Q( K( ~5 J; X
- db.users.find({name: {$type: 2}});
4 E2 F0 V; G' t2 l2 X; I) P' V R9 L
复制代码
5 o( U, w2 `, Y: G! M V/ \查询所有age字段是整型的
7 Y+ k/ Y/ X' _1 W/ [ O" p: r. E- db.users.find({age: {$type: 16}}); " W& C1 ?5 ~, {/ m
复制代码 ' k/ t% t5 x7 @& L$ @( R
对于字符字段,可以使用正则表达式 + u4 P W4 u7 i+ k7 Z3 s# R1 L
查询以字母b或者B带头的所有记录
B7 P; U/ r3 l- db.users.find({name: /^b.*/i});
: ~8 f; U B, a( |% |. I! z9 Y" K
复制代码
0 t1 E8 L! ~5 v% P# O% C$elemMatch(1.3.1及以上版本) / C i% v7 Q K- `( @
为数组的字段中匹配其中某个元素
( S8 L# y1 X/ C9 ~# m. \+ U
~: S% B/ @3 n7 C1 b5 b- J' mJavascript查询和$where查询
3 D, [$ _' F X* }3 v! g1 G1 D* T查询 age > 18 的记录,以下查询都一样 1 i: i& q* Z# g/ r
- db.users.find({age: {$gt: 18}}); 2 m% C3 Y; E3 E! |! [4 Z2 R
- db.users.find({$where: "this.age > 18"});
, b2 x6 H- y3 a2 E - db.users.find("this.age > 18"); / q" y# J; b* ~5 q. S0 q
- f = function() {return this.age > 18} db.users.find(f);
复制代码 4 y# B' G% k& }1 p) y
+ Q) F2 ]6 X) n$ j6 b% {排序sort() / ^0 U3 Z' j( r) d5 Q
以年龄升序asc ( `3 e; D0 f1 s8 m4 o
- db.users.find().sort({age: 1});
& O5 y3 o! l" u, f& T: ~* w! w1 D# y
复制代码
$ o3 U4 u; e: }& j0 Z以年龄降序desc
$ {) n; s% }6 Y8 A N2 M- db.users.find().sort({age: -1}); & J: Q( D7 K* O) u
复制代码 " d6 v- ~& ~6 E1 }0 B* X# [/ p/ c
限制返回记录数量limit()
' S* r/ F! A0 ~3 |1 H) b3 z返回5条记录
1 e7 v: C# l- P) P3 C/ g/ O* `- db.users.find().limit(5); 6 F, A: z* e" z. {4 R
复制代码 . r5 d8 u, V: _/ y3 t Z
返回3条记录并打印信息
3 B$ [; Z( p7 S; ?# R# G% x- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
4 F |9 w7 L8 R" f( d! M
复制代码
1 c! j! r8 A) r% i2 H结果
, \2 t3 s. n1 `- my age is 18
% |/ \# {; h9 Q( S - my age is 19
5 c4 }5 G; e+ y+ b1 s - my age is 20
复制代码
' `% W% y; `+ k( G9 r" ?% [& D5 }! F: i$ h \* U, k
限制返回记录的开始点skip() ) p; z; _7 ?9 |5 X
从第3条记录开始,返回5条记录(limit 3, 5) 5 v: X: ~. y; M+ x; j: [" J
- db.users.find().skip(3).limit(5);
- J0 ^1 S, [3 g, g% D4 h* C2 C
复制代码 9 v6 p* M( x# F0 Y/ D6 h+ O
查询记录条数count()
@) C9 M3 l4 C( l! U# Cdb.users.find().count();
/ N( Z1 [+ a. Y5 D: h/ ?! e3 c6 Idb.users.find({age:18}).count();
$ w- L. B3 a! Y5 E/ R以下返回的不是5,而是user表中所有的记录数量
% P ~$ N1 B: o6 M0 Z8 F( B; ^9 F1 \db.users.find().skip(10).limit(5).count();
# P* Z4 R* z. q' X* v+ r( R如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
6 c9 Z. X4 M5 f( i- db.users.find().skip(10).limit(5).count(true);
复制代码 1 b( X8 N& Z' \8 o3 U% {% i
, s2 y) O# e, Q: [* A, H- s分组group() ; \! V/ s3 y. Y: e% P
假设test表只有以下一条数据 4 e$ m/ G) ~, ^2 P b
- { domain: "www.mongodb.org"
! o# }+ c Z1 p3 k& a1 P - , invoked_at: {d:"2009-11-03", t:"17:14:05"} ) q# k2 m7 M( k8 ?6 S
- , response_time: 0.05
! b- i( _2 X M7 C( y1 N - , http_action: "GET /display/DOCS/Aggregation" * c8 v3 u1 U' i
- }
复制代码
! \# B& U! J4 `使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count; 7 \. d( E3 x0 @
- db.test.group( t T1 l" t3 S2 r3 ]/ z7 E+ C0 m
- { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
. R# i# W/ Y4 m2 I - , key: {http_action: true} 5 Y* k- X; Y4 k
- , initial: {count: 0, total_time:0} , M4 h: k: k1 D7 D' V( {+ \, u
- , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } , n- B0 K3 X+ J+ g8 D
- , finalize: function(out){ out.avg_time = out.total_time / out.count } % n, @2 G% A' b. T* } p
- } );
7 q& t1 R9 w6 }8 V# U( |
& ~* n- |( k5 ]1 d2 p- [
" e- X+ P4 D$ ?, X$ ^6 X6 X& Z - { 9 m# M- ^% Z- Z$ S* s0 ~0 Q& }
- "http_action" : "GET /display/DOCS/Aggregation",
8 q8 A6 i. Y0 s: r8 o3 x/ A# b - "count" : 1,
3 d2 f: p5 V7 z! M0 i' M - "total_time" : 0.05,
T( s7 J& z2 U2 K3 Z8 _ - "avg_time" : 0.05 ; B# Z) L5 z# K k w8 d
- } 8 E, W+ f: x: g% y3 i% z
- ]
复制代码
8 ~: E5 Z" Z, {% ^6 `! h/ k6 c/ B8 u
5 J( d0 d! E e. E$ o. A3 T
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: {/ K5 V3 V. i, U& G7 _/ Q
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
8 K2 Z1 N; W o( ^
1 |0 C/ |2 `" X
- U5 X7 B0 D" F相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码 & [+ O% R" L) C
6 k: ?/ z4 H# u1 {! F# r' {
他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码 1 F4 e x" ^* j& ~. k
$ t5 l( I! W/ n8 L
我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码 e1 ^. ]0 W! t6 [' K. Q, ~
% V- S1 f+ c" L3 v. y5 c! Q
我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码 ! r1 E: T* O8 M% i* `) c: w& \. h. n
* ^' n9 q: S2 L# | 输出如: - & {$ Q8 \9 {5 P9 s; v; c. a7 t0 ]9 b
- [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码 & X7 s: ~ H! }9 |
7 ^/ Y0 N, D8 L: x* N
- N3 h. @! y2 r" m- r! D
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"5 {# E& c5 c; n; s. {1 b
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"8 I# f% p# Y! [$ V }
- xmlns:context="http://www.springframework.org/schema/context"
9 n8 ^7 }; _- | e1 V6 w - xmlns:mongo="http://www.springframework.org/schema/data/mongo"
0 y. j5 w) [4 \3 O* U P0 }! g - xsi:schemaLocation="http://www.springframework.org/schema/beans$ i* U# a* k5 A2 z6 g! {' k: t
- http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
5 ?3 ~* }8 x1 Y; d - http://www.springframework.org/schema/context( k1 }' _* g0 {* o# l. Y
- http://www.springframework.org/schema/context/spring-context-3.1.xsd- ^7 f/ T8 B: |* U
- http://www.springframework.org/schema/data/mongo
; U, P3 M2 W, j, J - http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">* ^, ~& D K( s+ _ Y c
- 2 d" Q- P9 e3 p7 \, t
- <context:property-placeholder location="classpath:mongo.properties" />8 J( _( {# s9 i* A2 ~! V- ]
-
, J3 d/ n8 A8 q9 X1 q - <!-- Default bean name is 'mongo' -->* W5 e+ ]1 J1 V2 L9 X/ R( F- ]1 ~
- <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />$ ]% V* y1 y7 `) a' @. Q
-
9 B7 j. o( l. F0 }7 H - <mongo:db-factory id="mongoDbFactory"
, ^. ]; x$ M4 E- F4 n6 G. f' R% t - mongo-ref="mongo"
# |% X- Q2 l' L. n# T9 b5 a - dbname="mongotest" />* F) P d' Q- Z
-
: E6 Z7 \) V" n: L y2 t* n' U* ^ - <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
. T" y: o# k$ W. I; y - <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
( t7 j+ @' E+ z5 i( P3 | - </bean>& A' `9 [, G/ _/ O
- </beans>
复制代码 - z: ~# a% S; T
' Z- [7 o+ t& |# W max和min的测试: - @Test
9 {; n' L. N5 l4 Y/ _- a - public void testMaxAndMinAge() throws Exception {
5 |, ~9 q- g ~* L* m - Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
: `, |4 J- L- D" y5 v - Person result = mongoTemplate.findOne(q, Person.class);) s" R( ?% L2 @/ T4 _
- log.info(result);
% R: r6 {& `4 g - 9 K" C8 Q) x. F( f: O8 T! x8 X
- q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);2 Y6 y& z( H2 f
- result = mongoTemplate.findOne(q, Person.class);
, s, y& x) E* g - log.info(result);
% X, f$ ?- y: s* B1 ` - }
复制代码
8 ^, p, x* C) p; m8 ^' `' w. U6 S {' N: t: ?) w
distinct的测试: - @Test
* f* {7 D8 u+ q0 q; |" Y6 a. e2 J - public void testDistinct() throws Exception {2 g+ q. d/ W5 o; I4 f: G5 E
- List result = mongoTemplate.getCollection("person").distinct("myFriends");
3 U: ~" S& P" r% b5 ]3 ] - for (Object o : result) {
, `# M4 |! U [# `+ f8 u# f9 U - log.info(o);
K7 ^+ H3 E. F P - }) n- X* |0 G8 P1 A: P; z
-
- K9 J u: @/ l6 y/ B; h - log.info("==================================================================");
# N- p3 {& H. M, C4 J3 w+ Y% H* D - Query query = Query.query(Criteria.where("manId").is("123456"));$ x# P2 j5 A2 N/ J7 I6 Q
- result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());
* N# j. K9 F' r3 j9 A. S9 `/ {; V - for (Object o : result) {2 w, H5 F/ U' C
- log.info(o);
* z* O8 E5 n2 ^0 x% n! z8 q - }) k0 ?* k5 t0 o
-
) ]! B/ w; n) g - log.info("==================================================================");$ ?7 @1 d# z- v; C+ O8 S% D
- result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");8 V# j( E9 U R. ^ L
- for (Object o : result) {
1 a" M |% O- x6 A- q - log.info(o);3 \6 R1 A; r1 w9 m% U
- }* I) H& J# {% ^* k3 b8 d( j- A
- }
复制代码
) K6 L. I6 k) |
7 G& v ] a' O) x1 M ^ 输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567; I/ {4 U' ~% N! t3 W. l! I8 q
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 345678: @ w9 @, p: T+ k7 k6 n
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 456789, ]: j& H! T+ G0 h; r6 i
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654
# T6 _! K% N |( i - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni
3 K! ^1 b( w! [& T2 V - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
8 F- t0 [4 s6 ?3 D - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456
: C, y# [- V2 \# Y: ^3 W - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================# a- [; b1 r' M! g( `- H4 z
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
- S8 F- |( z6 O( x: t5 [4 d - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678' h, P& U. P5 N4 H, ~
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
' D$ L. t8 ^7 v9 z6 W$ r& O - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876544 J. @* R8 V, ?5 A9 c ~! _# ^
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================
8 j( K3 [6 ]% S# U' ~$ g$ \ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa0 } L. N/ [% G& y. f2 b$ Y
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
/ j2 V( i5 e; z6 T3 k7 O - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc- Z8 d H) k3 h: P+ ~; A2 X
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www- |4 T3 H' P" L% L* X
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx
7 O! }0 j" d7 B4 u' X! h/ } - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy8 t9 p! B$ ]. Q
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz
5 a4 k7 l& z$ W& @9 |" H - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr6 Q3 z* T1 p1 d: ~
- 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
复制代码
" l2 C, `( D$ n5 A) K/ Q) H
# n. L" X3 D0 e: j( a 这里我要特别说明一下, 当使用了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等信息。 : }# M- I9 ~8 y0 ] p
8 b" L8 @9 t' L( ~# ]! W( o8 n+ E. c# K
|