将 AND 和 OR 结合的 MongoDB 查询?


为了将 AND 和 OR 结合在 MongoDB 中,我们首先使用文档创建一个集合 −

>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" }

更新于:30-7 月 -2019

1 千 + 查看

助力您开启成功的 事业

完成课程,获得认证

立即开始
广告