將 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 千 + 檢視

助力您開啟成功的 事業

完成課程,獲得認證

立即開始
廣告
© . All rights reserved.