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