好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

MongoDB高级查询教程

 Mongodb一些常用的查询 WHERE查询

// i.e., select * from things where x=3 and y="foo" db.things.find( { x : 3, y : "foo" } );

 

db.things.find({j: {$ne: 3}, k: {$gt: 10} });

 

存储数组元素

db.things.insert({colors : ["blue", "black"]}) db.things.insert({colors : ["yellow", "orange", "red"]}) //查询结果 db.things.find({colors : {$ne : "red"}}) {"_id": ObjectId("4dc9acea045bbf04348f9691"), "colors": ["blue","black"]}

 

对比操作符

db.collection.find({ "field" : { $gt: value } } ); // greater than : field > value db.collection.find({ "field" : { $lt: value } } ); // less than : field < value db.collection.find({ "field" : { $gte: value } } ); // greater than or equal to : field >= value db.collection.find({ "field" : { $lte: value } } ); // less than or equal to : field <=

 

$all 全部属于

db.things.find( { a: { $all: [ 2, 3 ] } } )

 

$exists 字段存在

db.things.find( { a : { $exists : true } } ) db.things.find( { a : { $exists : false } } ) true返回存在字段a的数据,false返回不存在字度a的数据。

 

$mod 取模运算

db.things.find( { a : { $mod : [ 10 , 1 ] } } ) 条件相当于a % 10 == 1 即a除以10余数为1的。

 

$ne 不等于

db.things.find( { x : { $ne : 3 } } ) 条件相当于x<>3,即x不等于3。

 

$in 属于

db.things.find({j:{$in: [2,4,6]}}) 条件相当于j等于[2,4,6]中的任何一个。

 

$nin 不属于

db.things.find({j:{$nin: [2,4,6]}}) 条件相当于 j 不等于 [2,4,6] 中的任何一个。

 

$or 或 (注意:MongoDB 1.5.3后版本可用)

db.foo.find( { $or : [ { a : 1 } , { b : 2 } ] } ) 符合条件a=1的或者符合条件b=2的数据都会查询出来。

 

$size 数量,尺寸

db.things.find( { a : { $size: 1 } } ) 条件相当于a的值的数量是1(a必须是数组,一个值的情况不能算是数量为1的数组)。

 

$type 字段类型

db.things.find( { a : { $type : 2 } } ) 条件是a类型符合的话返回数据。

 

limit() skip()

这两个ME想连起来讲,他们就是你实现数据库分页的好帮手。 limit()控制返回结果数量,如果参数是0,则当作没有约束,limit()将不起作用。 skip()控制返回结果跳过多少数量,如果参数是0,则当作没有约束,skip()将不起作用,或者说跳过了0条。 例如: db.test.find().skip(5).limit(5) 结果就是取第6条到第10条数据。 snapshot() (没有尝试) count() 条数 返回结果集的条数。 db.test.count() 在加入skip()和limit()这两个操作时,要获得实际返回的结果数,需要一个参数true,否则返回的是符合查询条件的结果总数。 例子如下: > db.test.find().skip(5).limit(5).count() 9 > db.test.find().skip(5).limit(5).count(true) 4

11) $elemMatch

如果对象有一个元素是数组,那么$elemMatch可以匹配内数组内的元素: t.find( { x : { $elemMatch : { a : 1, b : { $gt : 1 } } } } ) { "_id" : ObjectId("4b5783300334000000000aa9"), "x" : [ { "a" : 1, "b" : 3 }, 7, { "b" : 99 }, { "a" : 11 } ] } $elemMatch : { a : 1, b : { $gt : 1 } } 所有的条件都要匹配上才行。 注意,上面的语句和下面是不一样的。 t.find( { "x.a" : 1, "x.b" : { $gt : 1 } } ) $elemMatch是匹配{ "a" : 1, "b" : 3 },而后面一句是匹配{ "b" : 99 }, { "a" : 11 }

12) 查询嵌入对象的值

db.postings.find( { "author.name" : "joe" } ); 注意用法是author.name,用一个点就行了。更详细的可以看这个链接: dot notation 举个例子: db.blog.save({ title : "My First Post", author: {name : "Jane", id : 1}}) 如果我们要查询 authors name 是Jane的, 我们可以这样: db.blog.findOne({"author.name" : "Jane"}) 如果不用点,那就需要用下面这句才能匹配: db.blog.findOne({"author" : {"name" : "Jane", "id" : 1}}) 下面这句: db.blog.findOne({"author" : {"name" : "Jane"}}) 是不能匹配的,因为mongodb对于子对象,他是精确匹配。

 

查看更多关于MongoDB高级查询教程的详细内容...

  阅读:47次