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