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