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