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