mongodb 条件查询

mongodb 常用条件查询

精确条件查询

返回满足条件的文档的所有字段 相当于 select from tb where xxx 中的

db.test.find({"name":"tom","age":15})
>{ "_id" : ObjectId("4fas8ecbb9ds549e96276f1a"), "name" : "tom", "age" : 15, "class" : "11" }

只返回满足条件的字段

db.test.find({"name":"tom","age":15},{"name":1})
>{ "_id" : ObjectId("4fas8ecbb9ds549e96276f1a"), "name" : "tom"}

也可以指定要剔除的字段

db.test.find({"name":"tom","age":15},{"name":0,"age":0})
>{ "_id" : ObjectId("4fas8ecbb9ds549e96276f1a"), "class" : "11"}

条件查询

mongodb 查询中的比较符号

mongodb 意义
$lt <
$lte <=
$gt >
$gte >=
$ne !=

// 大于等于 select * from db where age>=18 and age<=32
db.test.find({"age":{"$gte":18, "$lte":32}})

// 不等于 select * from db where name != 'tom'
db.test.find({"name":{"$ne":"tom"}})

// 包含 select * from db where name in ("tom","jerry")
db.test.find({"name":{"$in":["tom","jerry"]}})

// 不包含 select * from db where name not in ("tom","jerry")
db.test.find({"name":{"$nin":["tom","jerry"]}})

// 或 select * from db where name = 'tom' or age = 18
db.test.find({"$or": [{"name":"tom"}, {"age":18}]})

// 取反 select * from db where name != 'tom'
db.test.find({"name": {"$not": {"name":"tom"}})

正则查询

db.test.find({"name":/\w/i})

集合查询

返回所有 name 数组中包含 tom 的文档

db.test.find({"name":"tom"})
>{ "_id" : ObjectId("43d5a2f0b9a222a5276f21"), "name" : [ "tom", "jerry","jack" ] }
>{ "_id" : ObjectId("43d5a2f0b9a222a5276f22"), "name" : [ "tom", "jerry" ] }

$all 返回所有 name 数组中同时包含 tom 和 jerry 的文档且顺序无关.

db.test.find({"name":{$all:["tom","jerry"]}})
>{ "_id" : ObjectId("43d5a2f0b9a222a5276f21"), "name" : [ "tom", "jerry","jack" ] }
>{ "_id" : ObjectId("43d5a2f0b9a222a5276f22"), "name" : [ "tom", "jerry" ] }

返回所有 name 数组中和目标数组完全一致的文档 (顺序,值都要一致)

db.test.find({"name":["tom","jerry"]})
>{ "_id" : ObjectId("43d5a2f0b9a222a5276f22"), "name" : [ "tom", "jerry" ] }

返回所有指定下标的匹配对象,即 name[1] =="jerry"

db.test.find({"name.1":"jerry"})
>{ "_id" : ObjectId("43d5a2f0b9a222a5276f22"), "name" : [ "tom", "jerry" ] }

$slice 返回部分数组中的部分元素

db.test.find({},{"name": {"$slice":1}}) // 前第一个元素
db.test.find({},{"name": {"$slice":-1}}) // 最后一个元素
db.test.find({},{"name": {"$slice":[3,5]}}) // 从第3个元素开始,向后取5个元素

内嵌查询

对文档中嵌套数的组中的子文档进行查询

db.test.findOne()

{
    name:[{n:"tom",nickName:"tom1"}]
}

db.test.find({"name": {"$elemMatch": {"n":"tom","nickName":"tom1"}}}

游标查询

使用游标进行查询,可以有效精确地控制返回对象. 当我们使用 find 函数时,便会自动返回一个查询游标.

var cursor = db.test.find();
while (cursor.hasNext()) {
    print(cursor.next().name)
}

//所有的条件查询都会返回游标对象
var cursor1 db.test.find({"name":"tom"}).limit(1).skip(4);
留言:

称呼:*

邮件:

网站:

内容: