從 MongoDB 中巢狀在另一個數組內的陣列中刪除特定記錄?


要刪除特定記錄,請使用 $pull 運算子。首先讓我們建立一個包含文件的集合 −

> dbdeletingSpecificRecordDemoinsertOne(
   {
      "StudentDetails": [
         {
            "StudentName": "John",
            "StudentSubjectDetails": [
               {
                  "Subject": "MongoDB",
                  "Marks":45
               },
               {
                  "Subject": "MySQL",
                  "Marks":67
               }
            ]
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cf2210ab64a577be5a2bc06")
}

以下是查詢,它使用 find() 方法來顯示集合中的所有文件 −

> dbdeletingSpecificRecordDemofind()pretty();

這將生成以下文件 −

{
   "_id" : ObjectId("5cf2210ab64a577be5a2bc06"),
   "StudentDetails" : [
      {
         "StudentName" : "John",
         "StudentSubjectDetails" : [
            {
               "Subject" : "MongoDB",
               "Marks" : 45
            },
            {
               "Subject" : "MySQL",
               "Marks" : 67
            }
         ]
      }
   ]
}

以下是刪除巢狀在另一個數組中的陣列中特定記錄的查詢 −

> dbdeletingSpecificRecordDemoupdate({"_id": ObjectId("5cf2210ab64a577be5a2bc06"), "StudentDetailsStudentName" : "John"},
   {
      "$pull": {"StudentDetails$StudentSubjectDetails" : { "Marks":45 }}
   }, multi=true
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

讓我們再次檢查該文件 −

> dbdeletingSpecificRecordDemofind()pretty();

這將生成以下文件 −

{
   "_id" : ObjectId("5cf2210ab64a577be5a2bc06"),
   "StudentDetails" : [
      {
         "StudentName" : "John",
         "StudentSubjectDetails" : [
            {
               "Subject" : "MySQL",
               "Marks" : 67
            }
         ]
      }
   ]
}

更新於: 30-7-2019

144 次瀏覽

開啟你的 事業

透過完成課程來獲得認證

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