MongoDB 逻辑操作符与字段操作符

包含与不包含:in、nin

> db.accounts.find({"name":{$in:["alice2"]}}).pretty()
{ "_id" : "account1", "name" : "alice2", "balance" : 100 }
{
 "_id" : ObjectId("5d7f43abaecbd2bc0fa821b7"),
 "name" : "alice2",
 "balance" : 100
}

逻辑操作符:not、and、or、nor

not操作:获取余额不大于120的账号列表

> db.accounts.find({"balance":{$not:{$gt:120}}}).pretty()
{ "_id" : "account1", "name" : "alice2", "balance" : 100 }
{
 "_id" : ObjectId("5d7f43abaecbd2bc0fa821b7"),
 "name" : "alice2",
 "balance" : 100
}

and操作:获取name为alice2,且balance小于120的记录

> db.accounts.find({$and: [ { "name":"alice2" }, { "balance":{$lt:200} } ] } );
{ "_id" : "account1", "name" : "alice2", "balance" : 100 }
{ "_id" : ObjectId("5d7f43abaecbd2bc0fa821b7"), "name" : "alice2", "balance" : 100 }
# 上述查询语句,可以简写为
> db.accounts.find({ "name":"alice2", "balance":{$lt:200} });
# 当筛选条件,应用在同一个字段上的时候,也可以做简化
> db.accounts.find({"balance":{$lt:120,$gt:80} });
{ "_id" : "account1", "name" : "alice2", "balance" : 100 }
{ "_id" : ObjectId("5d7f43abaecbd2bc0fa821b7"), "name" : "alice2", "balance" : 100 }

字段操作符

exists 查询存在某个字段的记录

> db.accounts.find({"_id.name":{$exists:true}});
{ "_id" : { "name" : "david", "balance" : 200 }, "name" : "charlie", "balance" : 500 }
{ "_id" : { "balance" : 200, "name" : "david" }, "name" : "charlie", "balance" : 500 }

type 针对字段类型进行查询

> db.accounts.find({"_id":{$type:['string','objectId','object','null']}});

posted on 2020-04-05 22:32  思过崖灬  阅读(227)  评论(0编辑  收藏  举报

导航