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