|
版本一:+ T/ F$ W7 L3 |
7 q. g' e7 S" w1 ) . 大于,小于,大于或等于,小于或等于/ O, Z N/ q* x( P# F$ T
! G* E& O, j7 K3 I! W1 Y3 }
$gt:大于
! C: Q; o9 q' W$lt:小于- G) A6 o* i% Z- [0 A$ n4 g
$gte:大于或等于% `- K. J8 ~! w4 o, k& G
$lte:小于或等于6 }3 n: t: @. e( ~( J% A
& h& x) h1 i# C4 E7 d例子: - db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value. K9 R0 l. Q! k
- db.collection.find({ "field" : { $lt: value } } ); // less than : field < value" g( T3 j: m7 ?9 x% F
- db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value8 {& E9 T3 Q* L1 i
- db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <= value
复制代码 6 f- ~1 V: Z/ I, {, F5 d. u
如查询j大于3,小于4: - db.things.find({j : {$lt: 3}});
. Z# x+ @+ |7 l - db.things.find({j : {$gte: 4}});
复制代码 u( Z4 j3 B3 z
也可以合并在一条语句内: - db.collection.find({ "field" : { $gt: value1, $lt: value2 } } ); // value1 < field < value
复制代码
, ^) c* }2 T; e; B0 ^: |# P8 c. j$ w4 @
1 @. P: k. _3 s6 d) h2 h% H- ^
2) 不等于 $ne 例子: - db.things.find( { x : { $ne : 3 } } );
复制代码
, E9 I- s$ ~# j R d$ [7 h( ?3) in 和 not in ($in $nin), I6 \! {& L3 _
# i( b W9 h, n% ]: N/ q$ k语法: - db.collection.find( { "field" : { $in : array } } );
复制代码
+ v; V$ z. Y0 Y' b7 E* e& f例子: - db.things.find({j:{$in: [2,4,6]}});
^% c+ v& }6 { - db.things.find({j:{$nin: [2,4,6]}});
复制代码
% k8 l, {1 y4 T+ E/ X, u7 U3 Y# a
3 d+ ~! I) K0 e4 |. ^5 e4) 取模运算$mod
6 N3 x# P6 ]8 X2 E9 o0 n+ v* s: F& l) I# k0 V v
如下面的运算:
- db.things.find( "this.a % 10 == 1")
复制代码 ! t! ]( ]8 h+ `# x# }# |
可用$mod代替: - db.things.find( { a : { $mod : [ 10 , 1 ] } } )
复制代码
1 `2 h2 b8 _ X2 U3 _5 l
5 _+ k! h" ~0 }6 T1 L5) $all# H% J- S" }: ]2 o
E0 A$ O/ f$ ^ O$all和$in类似,但是他需要匹配条件内所有的值:
- B- G1 D& B6 n4 c j/ ]! |7 d
5 e/ v0 H/ ~2 {如有一个对象:$ \8 s' Z0 A( k1 ]; h, I1 o
" H, s- ^# a+ G9 s1 o
下面这个条件是可以匹配的: - db.things.find( { a: { $all: [ 2, 3 ] } } );
复制代码
$ k& X& r" n6 b4 x但是下面这个条件就不行了: - db.things.find( { a: { $all: [ 2, 3, 4 ] } } );
复制代码
( e H9 f! `% ]$ C, `
2 `1 J1 j) |+ | j6) $size: L# e# }( D3 j" E9 J
8 Q. A6 Z6 }% I! @/ b$size是匹配数组内的元素数量的,如有一个对象:{a:["foo"]},他只有一个元素:
# @; E& l: f9 v( H d2 A( [9 p6 |) ~
下面的语句就可以匹配:
- db.things.find( { a : { $size: 1 } } );
复制代码
8 k' S8 Y, V- r- Z: G0 J% P! `官网上说不能用来匹配一个范围内的元素,如果想找$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 y7 S% r @& K% a& b* {% e7)$exists $exists用来判断一个元素是否存在: 如: - db.things.find( { a : { $exists : true } } ); // 如果存在元素a,就返回
- s3 s1 {) i' Q6 E( J - db.things.find( { a : { $exists : false } } ); // 如果不存在元素a,就返回
复制代码 4 g5 l/ Z% s0 r6 H; a+ Q; b8 D; X
8) $type $type 基于 bson type来匹配一个元素的类型,像是按照类型ID来匹配,不过我没找到bson类型和id对照表。 - db.things.find( { a : { $type : 2 } } ); // matches if a is a string1 Q4 ]) ] w3 g; k B
- db.things.find( { a : { $type : 16 } } ); // matches if a is an int
复制代码
5 C5 e1 ^ h/ \1 E4 b* Z; B# P. {2 Z9)正则表达式6 V% G0 `, ^2 R
4 r. H3 L7 D ]- h
mongo支持正则表达式,如: - db.customers.find( { name : /acme.*corp/i } ); // 后面的i的意思是区分大小写
复制代码
& u8 r3 m+ c; p0 w- X j10) 查询数据内的值- {0 w! n9 J9 C' F9 h
0 h% w3 x: k C! q1 e
下面的查询是查询colors内red的记录,如果colors元素是一个数据,数据库将遍历这个数组的元素来查询。 - db.things.find( { colors : "red" } );
复制代码
& J6 J; s7 k+ d% H' H6 j11) $elemMatch
7 _( Y. V6 Z6 g9 O8 Z6 v
. o7 `2 ]! R7 [# X如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: - > t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) % ?3 P1 f9 S! h% C) J% Z
- { "_id" : ObjectId("4b5783300334000000000aa9"),
, S1 n/ a; a2 j6 K/ D! _ - "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ]
7 S. o2 \2 I: ~5 V - }
复制代码 @ A4 k, ~& |! c* Q
$elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。注意,上面的语句和下面是不一样的。 > t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } )- @: B1 r9 g- O1 ~
$elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 } ! F: ^1 s7 I/ n$ f3 s ?) B7 v9 @
|$ o6 P0 I3 t* X& w' o! f, A/ @
12) 查询嵌入对象的值 - db.postings.find( { "author.name" : "joe" } );
复制代码 3 Y$ w" P* \9 P+ n
举个例子: - > db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}})
复制代码
2 v# ]% [1 }: m: O( w如果我们要查询 authors name 是Jane的, 我们可以这样: - > db.blog.findOne({"author.name" : "Jane"})
复制代码 ( ~4 A$ ?7 ^/ T% @6 ~/ M( P
如果不用点,那就需要用下面这句才能匹配: - db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}})
复制代码
/ M7 x3 _2 F: s% _: l下面这句: - db.blog.findOne({"author" : {"name" : "Jane"}})
复制代码 # H( T5 U+ `# c+ c! k
是不能匹配的,因为mongodb对于子对象,他是精确匹配。 4 @7 a6 g' Y8 L5 ]
13) 元操作符 $not 取反 如: - db.customers.find( { name : { $not : /acme.*corp/i } } );
; P8 J7 P- j) a$ _$ | - db.things.find( { a : { $not : { $mod : [ 10 , 1 ] } } } );
复制代码
( p# x6 r; @ Q. X3 \ c' `( S8 ushell 环境下的操作: 1. 超级用户相关: 1. #进入数据库admin
6 Z9 m! O% j! o, @9 P' a1 W* X5 J3 b+ H: L1 L/ \
2. #增加或修改用户密码 3. #查看用户列表 4. #用户认证 5. #删除用户 6. #查看所有用户 7. #查看所有数据库 8. #查看所有的collection 9. #查看各collection的状态 - db.printCollectionStats()
复制代码 1 ~+ w2 k) u, v+ v5 j( a7 r4 R. n
10. #查看主从复制状态 - db.printReplicationInfo()
复制代码
- z9 E) l( b% h# D: ^! b 11. #修复数据库 12. #设置记录profiling,0=off 1=slow 2=all
' X3 e+ W9 D& T% [6 z `. @! s9 I 13. #查看profiling 14. #拷贝数据库 - db.copyDatabase('mail_addr','mail_addr_tmp')
复制代码 ' n( z" F! v* R( ?0 G
15. #删除collection 16. #删除当前的数据库 2. 增删改 1. #存储嵌套的对象 - db.foo.save({'name':'ysz','address':{'city':'beijing','post':100096},'phone':[138,139]})
复制代码 0 |! c. S& K( }
2. #存储数组对象 - db.user_addr.save({'Uid':'yushunzhi@sohu.com','Al':['test-1@sohu.com','test-2@sohu.com']})
复制代码
; n/ X( K& s+ o [* j: H 3. #根据query条件修改,如果不存在则插入,允许修改多条记录 - db.foo.update({'yy':5},{'$set':{'xx':2}},upsert=true,multi=true)
复制代码 7 A8 l. L2 V) i1 L
4. #删除yy=5的记录
. l- b$ E$ m( f$ z, l* }- b 5. #删除所有的记录
5 X! g; B$ L: C& F8 u( C5 Y" k 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() * C. y& l7 h; G0 K0 y8 F- V
6. 高级查询 条件操作符
M; l: ]# i* p- Q+ [- $gt : >
: \8 r2 @( f6 t% { - $lt : < ( m; m8 C& `: c. J4 k* a# i5 ]0 j! H- Q
- $gte: >=
+ x- E% N/ e2 B% r! k- m. I5 N - $lte: <=
`) v; d3 c0 Z; W5 L7 k9 d5 z* J - $ne : !=、<>
3 Q, Q) r' C- A: A+ [ - $in : in 5 F9 e! Y6 O; \/ y; \: p
- $nin: not in 6 V, s9 g. \4 A: Z% P9 R
- $all: all
/ G' w" i. b7 T8 b - $not: 反匹配(1.3.3及以上版本)
复制代码 5 G1 Z. c; G7 z/ o7 D
9 Z1 n3 B$ s0 E0 j查询 name <> "bruce" and age >= 18 的数据 . M5 e% C7 `3 C# b; ^& e7 e6 y
- db.users.find({name: {$ne: "bruce"}, age: {$gte: 18}});
复制代码
% n3 S7 h" U$ Z8 |# x8 X$ X! [
' B* V- o& Z6 P2 @查询 creation_date > '2010-01-01' and creation_date <= '2010-12-31' 的数据
( ^+ ~& `7 T) ]% |- A) P$ j- db.users.find({creation_date:{$gt:new Date(2010,0,1), $lte:new Date(2010,11,31)});
复制代码
! A& }# l% g4 \0 F0 U8 w r' q2 E3 X* U; P
查询 age in (20,22,24,26) 的数据
4 W2 Y/ c% b- E K- db.users.find({age: {$in: [20,22,24,26]}});
复制代码 ( V0 ]" M& \2 c2 G( f/ V
$ o8 O* C4 O& v. K查询 age取模10等于0 的数据
$ Y9 w" G5 q* v6 H" L1 b- db.users.find('this.age % 10 == 0');
复制代码
: W3 d+ E9 c2 z' [8 d" w. u4 N或者 : E. E' E: P f9 L
- db.users.find({age : {$mod : [10, 0]}});
复制代码 ) a. T' v! Q1 ~. B% f: r# ~7 q
1 z: m5 N$ l9 E- G( u' N匹配所有
3 ]: s2 `6 |# A5 }( G- db.users.find({favorite_number : {$all : [6, 8]}});
复制代码
$ {5 f, r6 Z# q9 G4 b7 D可以查询出{name: 'David', age: 26, favorite_number: [ 6, 8, 9 ] } 8 Y! I5 }# W/ \1 ]6 w
可以不查询出{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }
0 n) q, h' Q* O& r+ m) q* R/ k2 U2 y+ x* c; I# d/ b1 E# m1 V3 ^
查询不匹配name=B*带头的记录
. R4 r1 j" P" S: Q- db.users.find({name: {$not: /^B.*/}});
复制代码 # i* n2 R- v8 K0 }! a& W# O! h
查询 age取模10不等于0 的数据 1 U* F+ q. l- A) f) z* Y" i1 h" T
- db.users.find({age : {$not: {$mod : [10, 0]}}});
复制代码 7 q( {- u `9 {9 T# v
% j. v2 n6 b( @( X#返回部分字段
( l% N. B( E$ @% O% J" u选择返回age和_id字段(_id字段总是会被返回) $ h+ N1 B1 `- f$ J2 @
- db.users.find({}, {age:1}); $ R0 p; g8 h( L, }6 B
- db.users.find({}, {age:3}); + F4 {+ X |$ ]0 v% w- i
- db.users.find({}, {age:true});
# b F( {) _$ I$ q6 E0 `4 Q' U - db.users.find({ name : "bruce" }, {age:1});
复制代码 ! h, \0 L4 P4 C3 S
0为false, 非0为true
: y6 D' J; |* }9 ^5 f* O; L2 w
选择返回age、address和_id字段
6 r' P' @* ?2 T$ r1 K- db.users.find({ name : "bruce" }, {age:1, address:1});
复制代码
6 {0 J8 c' z6 {9 Y% B/ N3 V; t' \2 F, m' X+ T) \
排除返回age、address和_id字段 ; v8 a) I L$ \% b, n* `) t+ r- |/ g
- db.users.find({}, {age:0, address:false}); 8 G3 ~9 L- A* P9 ~
- db.users.find({ name : "bruce" }, {age:0, address:false});
复制代码
( t; h3 E# v9 ^. a* { }+ D" j1 k$ x9 g0 b0 q" x2 ^, f. M/ H
数组元素个数判断 5 T- s$ T- O% }
对于{name: 'David', age: 26, favorite_number: [ 6, 7, 9 ] }记录 # {$ F7 B$ c& q' O# O
匹配db.users.find({favorite_number: {$size: 3}});
2 H" F# j' h) F1 a不匹配db.users.find({favorite_number: {$size: 2}});
& x3 [, L. v1 [4 s, w
) B& g5 u. y! F7 P0 _$exists判断字段是否存在
3 N* w$ d, O& ?$ K) y% H3 z查询所有存在name字段的记录 . }0 ^% Q6 _! _; t
- db.users.find({name: {$exists: true}});
复制代码
1 F, [9 g0 Y4 f查询所有不存在phone字段的记录
; S. n4 X' l0 H9 S- db.users.find({phone: {$exists: false}});
复制代码
' }3 [& n1 u6 ?2 O
! V, y- I! {$ X2 F$type判断字段类型
7 h6 [4 g- x4 Y查询所有name字段是字符类型的
1 t6 j% x( ^% k$ K* Y1 b- db.users.find({name: {$type: 2}}); ! [, D4 H, g! y! A5 `6 a
复制代码 + o8 Z8 t5 J7 i& F, L' T/ V
查询所有age字段是整型的 * {0 J" f( [- O: H7 P1 t4 ^
- db.users.find({age: {$type: 16}}); ' ]3 b2 c5 Q& u; E0 _
复制代码
5 K+ u" P% _+ T5 w& F0 T/ C! l2 \5 g对于字符字段,可以使用正则表达式 6 W/ k( w- D5 F' `
查询以字母b或者B带头的所有记录 # }& H8 r5 C% A% A
- db.users.find({name: /^b.*/i});
2 M! Z& q3 N7 H1 E
复制代码
2 C3 N+ P/ R# c$ L, o$elemMatch(1.3.1及以上版本) ! R" Q, [- z7 U5 U5 H+ r6 r
为数组的字段中匹配其中某个元素
& J# N2 i4 b$ b: Q( o/ o& s* r V
Javascript查询和$where查询 4 e( v/ e9 Y% L/ O( \2 [
查询 age > 18 的记录,以下查询都一样 , D5 E1 S& G5 x
- db.users.find({age: {$gt: 18}});
0 K- Y2 [1 P7 Q+ p - db.users.find({$where: "this.age > 18"}); : n# Z8 G% B8 t5 j$ g
- db.users.find("this.age > 18"); ! w1 c1 \5 N5 s, f
- f = function() {return this.age > 18} db.users.find(f);
复制代码 : s5 j7 n* z8 m5 G/ i
6 x, H6 a$ P2 n: k& h
排序sort() 7 x) S: @- w. w7 |4 X
以年龄升序asc 8 Q: E/ p% l* f \3 C- H
- db.users.find().sort({age: 1}); + ]7 c6 h+ R+ V5 x7 Z, s9 V
复制代码
$ M M" W1 @- K' F b/ r0 t以年龄降序desc 8 X+ p+ }8 e% {. K* l0 `( _+ I. `* Z
- db.users.find().sort({age: -1}); ' G3 h& ]- R) f' [7 [' |
复制代码
* y. S4 `$ b1 z2 v" R1 G限制返回记录数量limit()
% n: i- N8 g7 t% T+ e( a返回5条记录 : L; v6 M4 u/ \/ ]/ e& S) |5 c8 s
- db.users.find().limit(5);
# i$ K9 s' A' G" }
复制代码 5 a' e/ z6 Z9 {$ f, d7 C) l/ t5 O, n6 h+ W
返回3条记录并打印信息 0 u0 X5 z1 i7 A7 e
- db.users.find().limit(3).forEach(function(user) {print('my age is ' + user.age)});
2 d% X- D0 s6 d# k0 U/ Q
复制代码
! q" t! O g" Q8 `7 r; b) m结果
( i+ l) g6 g" `9 D, W- my age is 18 3 P% O( b4 l( s
- my age is 19
L1 d( @. \3 S T Y4 a - my age is 20
复制代码
: `; t v1 H/ P- @9 Z @) ?" l& f! z" i0 ^) ^4 f
限制返回记录的开始点skip() - [2 X3 P3 F; X7 ]: O: E
从第3条记录开始,返回5条记录(limit 3, 5)
Z. D0 p$ B& I. ~& m+ l3 u- db.users.find().skip(3).limit(5);
0 r+ j3 l% F# H4 R" W( H
复制代码
4 j0 |0 l/ G9 {5 x; b查询记录条数count() , F, h! O4 r( F, V( d$ P1 A6 B
db.users.find().count();
( ]4 |) @% h" ~8 n; _; g. vdb.users.find({age:18}).count(); 0 w2 o" F0 {. K. K( @' w, I7 q
以下返回的不是5,而是user表中所有的记录数量
8 m+ `& g. R& v- wdb.users.find().skip(10).limit(5).count(); 9 v- V5 v# t; X. z i/ Z! k& L7 l
如果要返回限制之后的记录数量,要使用count(true)或者count(非0)
h& ?2 L' h+ ~3 ?- S% j- db.users.find().skip(10).limit(5).count(true);
复制代码
( r7 H7 W7 M5 ~8 N {$ Y+ u' n. U+ r# l. X8 R* V% ?
分组group() # u& f/ { u$ f7 ~3 s. F4 E' y
假设test表只有以下一条数据 1 q, K3 b- X- \. |. ]7 I
- { domain: "www.mongodb.org" ( h) G9 U, P( c# x8 S8 l/ F5 E
- , invoked_at: {d:"2009-11-03", t:"17:14:05"}
. A' K2 r/ V) E6 R p) ^1 b$ d - , response_time: 0.05 5 t+ v( }' v6 D9 \
- , http_action: "GET /display/DOCS/Aggregation" 8 \& ]& o" K: d8 K* H$ r i: R
- }
复制代码
; O0 S5 h6 p( I+ P8 K3 ]使用group统计test表11月份的数据count:count(*)、total_time:sum(response_time)、avg_time:total_time/count;
: y7 k; H3 [; H" _2 p# s- db.test.group( . |* @" g: m' V0 j( @! k
- { cond: {"invoked_at.d": {$gt: "2009-11", $lt: "2009-12"}}
t; m6 d* l: m3 ~ s - , key: {http_action: true} - X8 ~" X2 @2 e' P% n1 |; ~
- , initial: {count: 0, total_time:0}
, y6 _ i9 }: Y9 ]! h - , reduce: function(doc, out){ out.count++; out.total_time+=doc.response_time } 2 {/ X- [* @$ m2 y& g
- , finalize: function(out){ out.avg_time = out.total_time / out.count }
. ^) D. y, v O' e - } ); 4 d8 q2 s2 [ z* I4 ^/ D* Z
3 X: z! O0 q$ u, [& x- [
. @' N& X4 j4 a8 |( K ^5 J$ j% c% b - { ! I! R# z% k! ^4 ]7 j: H2 o
- "http_action" : "GET /display/DOCS/Aggregation", , x6 V2 d- k o, P0 n
- "count" : 1, * [, d! B% v( b, Y! C! | b
- "total_time" : 0.05,
( c' _! @+ Q; K f& I$ ? - "avg_time" : 0.05 * A: \* n9 [' _' J0 |7 z- s5 j
- } 8 w8 ~) k6 k* }8 C% _4 X' q: x f
- ]
复制代码 5 m9 d4 V4 I9 f
4 j# Q" C9 g! B2 e9 Q8 ^
7 I" r4 G% S5 ?& ?3 e1 T' WMongoDB 高级聚合查询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
6 W5 @" y; i4 {! @: G) G
我和同事在测试Mongo时,索引还写了不到一半,他想查询某个字段的最大值,结果找了半天文档也没找到关于max的函数。我也很纳闷这是常规函数啊怎么不提供? 后来经过翻阅资料确定Mongo确实不提供直接的max和min函数。但是可以通过间接的方式[sort 和 limit]实现这个。 要查询最大值我们只需要把结果集按照降序排列,取第一个值就是了。 如我的例子,我想取得集合中年龄最大的人。 - db.person.find({}).sort({"age" : -1}).limit(1)
复制代码
5 I4 k6 ?' Q* H$ o m4 {% t1 ^$ ? K/ h. x% W0 s1 k8 k
% d- \; S5 u8 D' `. ^) {4 ?
相反如果想要年龄最小的人,只需要把sort中改为{“age”:1}就可以了。 当然我们使用了sort,对于小数量的文档是没问题的。当对于大量数据需要给age建立索引,否则这个操作很耗时。 - distinct0 B5 _' R; W j3 D7 L" J# ]
MongoDB的destinct命令是获取特定字段中不同值列表的最简单工具。该命令适用于普通字段,数组字段[myFriends]和数组内嵌文档[fruits]. 如上面的图片,我认为fruits和myFriends字段是不同的。网上很多资料和例子都没说到这个情景,因为我们也业务是fruits这样的模型,我测试了。对于fruits.fruitId他也是可行的。 如上面的表结构,我想统计所有的喜欢的水果。 - db.person.distinct("fruits.fruitId") // 查找对象里引入对象的值,直接加.
复制代码
5 P1 L* U5 b) c1 \7 ^6 T' U' s# P' x
他成功执行了。输出如: - [ "aaa", "bbb", "ccc", "www", "xxx", "yyy", "zzz", "rrr" ]
复制代码 ' g) Y$ `8 e7 }5 Y
2 `( I& C9 `$ g0 s2 A" | 我想统计集合中共有多少个人[按名字吧] - db.person.distinct("manName")
复制代码
& N9 {) m, ]+ j* g4 F# {3 q( t3 [0 X/ ~* b
我想统计指定个数的人的共同关注的朋友。 - db.person.distinct("myFriends", {"manName" : {"$in" : ["ZhenQin", "YangYan"]}})
复制代码 8 Z( L+ K% M2 E6 S1 X9 r
7 }, ?/ }6 s1 V% v- h4 D; U
输出如: -
( ~" B- x. T1 L% h: k* P3 ? - [ "234567", "345678", "456789", "987654", "ni", "wo" ]
复制代码 ( l% \/ d7 T3 g( {
. C: F. R5 I+ ?" ~
) Q9 F2 B- K- N0 f* O+ I
那么我使用Java呢? 我只是在演示Mongo的命令,用Spring Data Mongo是怎么操作的? Spring Schema: - <beans xmlns="http://www.springframework.org/schema/beans"
5 v5 X+ b8 M+ C$ i& f9 `7 Z. D - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance": a6 L7 s- V' u6 }; e$ _" |, u
- xmlns:context="http://www.springframework.org/schema/context") ?; S* o; E p% P
- xmlns:mongo="http://www.springframework.org/schema/data/mongo"$ O$ i. R9 y* R6 @4 E- |0 U/ x$ z
- xsi:schemaLocation="http://www.springframework.org/schema/beans
% I; K! l; @# I - http://www.springframework.org/schema/beans/spring-beans-3.0.xsd, o* ?# b" [/ t3 n7 S: x7 p
- http://www.springframework.org/schema/context c) v; I! _0 r' o% W" k
- http://www.springframework.org/schema/context/spring-context-3.1.xsd
" X# U# V( [# p, [0 J2 {8 V - http://www.springframework.org/schema/data/mongo
' o( d* e, D: a* N+ _ - http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">
! l Z6 K6 U" Z9 j+ q - 3 u4 Y0 \2 ?. b# o. d
- <context:property-placeholder location="classpath:mongo.properties" />2 f6 O' f1 `+ m; }
- ) m# Y) U- ^5 W; H# l" H5 W
- <!-- Default bean name is 'mongo' -->/ `8 d6 V6 f a+ u B: O9 e6 e
- <mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" />
. c/ g$ `( U' P- H* S - ( f' p! y( [. y# {1 @
- <mongo:db-factory id="mongoDbFactory"
: \% X# L( u7 p" G# U) W+ | - mongo-ref="mongo"
$ g" ~+ z) X# x - dbname="mongotest" />
: P( e: y. A6 c( S l" S -
5 Q0 J' p# J+ z. d - <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
$ ]+ e- B+ v* I- h9 j - <constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>5 w0 K& h |# Y7 f" o% f# }# _/ H" q
- </bean>9 t7 b1 R; u. B
- </beans>
复制代码
/ k. K0 ]4 k$ C" ^
+ u; @' }% j7 H w/ o max和min的测试: - @Test
8 J% y0 b/ i5 R; U8 s! e - public void testMaxAndMinAge() throws Exception {
Q& P! \% b( _, p9 z; A- j( r - Query q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.ASC, "age"))).limit(1);
8 m; m" h2 i; `. d - Person result = mongoTemplate.findOne(q, Person.class);- N: p; P; x. d+ A1 V
- log.info(result);9 `+ Z: g a2 M6 q; I3 M9 a$ @! A
- * ]1 P- ^* a( c( I6 l& c( o
- q = new BasicQuery("{}").with(new Sort(new Sort.Order(Sort.Direction.DESC, "age"))).limit(1);6 K1 F9 `; k2 e. n0 `5 K
- result = mongoTemplate.findOne(q, Person.class);0 e; b, L1 ~3 @! Z6 a
- log.info(result);9 b2 @# @% Q, o7 i! _3 Q+ F5 {! q
- }
复制代码 & r! V* I' f! R! h
' _. {1 R( V; ]5 I V' ]
distinct的测试: - @Test1 }( p2 `8 y d
- public void testDistinct() throws Exception {
0 z% D8 t+ O* ^- b; } - List result = mongoTemplate.getCollection("person").distinct("myFriends");: E0 r2 C! V+ q/ g* T
- for (Object o : result) {
; i% R0 ]8 @' s" z; p' M" } - log.info(o);/ }5 d& ~- J9 ` F0 V7 A" M
- }
M9 D( F& t7 q* H. W) X+ ] - + F+ N; _. {5 B
- log.info("==================================================================");/ I/ b. N* A- ^
- Query query = Query.query(Criteria.where("manId").is("123456"));+ N; k! l% s0 w% z1 C% F$ Y+ Z1 |
- result = mongoTemplate.getCollection("person").distinct("myFriends", query.getQueryObject());4 i/ |) T1 ]% N5 M3 L, ^+ J
- for (Object o : result) {# ]' Q: w$ _6 `5 N: X
- log.info(o);1 K3 @" V6 E( A* E, v) q
- }
3 ~# h3 Q8 O; m+ ^ - . q; B3 h- [, j: v) t: ~* `+ }
- log.info("==================================================================");8 H# O6 G- }1 P' l) N! U
- result = mongoTemplate.getCollection("person").distinct("fruits.fruitId");
7 I; ^: N( f. i: D* P - for (Object o : result) {
/ R: x8 C. N6 ^2 Y$ s! V" O - log.info(o);$ g% W& R6 c b# X8 t
- }" i; v9 h4 b3 a8 L! k1 Q
- }
复制代码
: @4 ?, ]7 z7 T8 W6 u3 n, Y- J$ V/ L D
输出的结果为: - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 234567
9 w+ b# _' v; [ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 3456788 }7 A' w/ p9 Y; u1 K1 k
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 4567892 Q5 u* e3 H4 ]& r
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 987654& v6 z# t# x7 _9 v
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] ni% o; `- k# u; @* k# y7 i" q
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] wo
" C3 r* Z( }; ^2 n' v - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(72)] 123456 P0 O( P5 X3 \: W$ V8 v
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(75)] ==================================================================# v5 |$ h5 _. K+ b% ~
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 234567
9 n5 e* H) |! Q. s" [5 g1 K4 L - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 345678; B& _, W5 i) u+ m6 h
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 456789
+ B# j4 N8 @3 g' Z: |7 | - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(79)] 9876540 M$ e/ {2 e- g7 L; L. f
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(82)] ==================================================================, Y# m" Q; N/ K! W: f+ [: z" |
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] aaa6 m; \, ]- G( b' t0 t f$ R
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] bbb
) h+ q* ~2 \* Z. K - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] ccc* e# P. h9 ]/ ^; p/ c8 d7 D
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] www
7 g' b) j2 w1 c6 \) i, G! \ - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] xxx1 W' g2 U# g5 V( X0 M! g' Q
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] yyy
1 X! P; P& r- N - 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] zzz5 ~! }! ^- q. e5 \+ T1 M
- 12-22 14:13:45 [INFO] [t.MongoAdvaceQueryTest(85)] rrr
- v/ B+ W1 P0 z: i; 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
复制代码 ' W4 n% ]" `- `# H. _# s
- X$ @8 L7 {5 \! f! \ 这里我要特别说明一下, 当使用了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等信息。
6 f: e9 C7 w6 y9 h+ U T9 {& N, y, [& ]& t9 u( ^/ Z! C
8 V) K9 p2 M7 O- W
|