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