MongoDB查询合并AND和OR?
为了在MongoDB中结合AND&OR,让我们首先创建一个包含文档的集合-
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"John","StudentAge":23,"StudentSkill":"MongoDB"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd306dcb64f4b851c3a13e2")
}
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"Larry","StudentAge":21,"StudentSkill":"MySQL"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd306f3b64f4b851c3a13e3")
}
>db.combinedAndOrDemo.insertOne({"StudentFirstName":"Sam","StudentAge":24,"StudentSkill":"SQL Server"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd30701b64f4b851c3a13e4")
}以下是在find()方法的帮助下显示集合中所有文档的查询-
> db.combinedAndOrDemo.find().pretty();
这将产生以下输出-
{
"_id" : ObjectId("5cd306dcb64f4b851c3a13e2"),
"StudentFirstName" : "John",
"StudentAge" : 23,
"StudentSkill" : "MongoDB"
}
{
"_id" : ObjectId("5cd306f3b64f4b851c3a13e3"),
"StudentFirstName" : "Larry",
"StudentAge" : 21,
"StudentSkill" : "MySQL"
}
{
"_id" : ObjectId("5cd30701b64f4b851c3a13e4"),
"StudentFirstName" : "Sam",
"StudentAge" : 24,
"StudentSkill" : "SQL Server"
}以下是结合AND&OR的查询-
> db.combinedAndOrDemo.find( {"$or":[ {"$and": [{"StudentFirstName": "John"}, {"_id": ObjectId("5cd306dcb64f4b851c3a13e2")}] }, {"StudentSkill" : "MongoDB" } ] } );这将产生以下输出-
{ "_id" : ObjectId("5cd306dcb64f4b851c3a13e2"), "StudentFirstName" : "John", "StudentAge" : 23, "StudentSkill" : "MongoDB" }