如何在 MongoDB 使用 $pull 刪除陣列內的文件?


你需要使用 update 命令和 $pull 運算子來刪除陣列中的文件。讓我們建立一個帶有文件的集合。以下是查詢

> db.deleteDocumentsDemo.insertOne(
... {
...    "_id":100,
...    "StudentsDetails" : [
...       {
...          "StudentId" : 1,
...          "StudentName" : "John"
...       },
...       {
...          "StudentId" : 2,
...          "StudentName" : "Carol"
...       },
...       {
...          "StudentId" : 3,
...          "StudentName" : "Sam"
...       },
...       {
...          "StudentId" : 4,
...          "StudentName" : "Mike"
...       }
...    ]
... }
...
... );
{ "acknowledged" : true, "insertedId" : 100 }
> db.deleteDocumentsDemo.insertOne(
... {
...    "_id":200,
...    "StudentsDetails" : [
...       {
...          "StudentId" : 5,
...          "StudentName" : "David"
...       },
...       {
...          "StudentId" : 6,
...          "StudentName" : "Ramit"
...       },
...       {
...          "StudentId" : 7,
...          "StudentName" : "Adam"
...       },
...       {
...          "StudentId" : 8,
...          "StudentName" : "Larry"
...       }
...    ]
... }
...
... );
{ "acknowledged" : true, "insertedId" : 200 }

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

> db.deleteDocumentsDemo.find().pretty();

這將產生以下輸出

{
   "_id" : 100,
   "StudentsDetails" : [
      {
         "StudentId" : 1,
         "StudentName" : "John"
      },
      {
         "StudentId" : 2,
         "StudentName" : "Carol"
      },
      {
         "StudentId" : 3,
         "StudentName" : "Sam"
      },
      {
         "StudentId" : 4,
         "StudentName" : "Mike"
      }
   ]
}
{
   "_id" : 200,
   "StudentsDetails" : [
      {
         "StudentId" : 5,
         "StudentName" : "David"
      },
      {
         "StudentId" : 6,
         "StudentName" : "Ramit"
      },
      {
         "StudentId" : 7,
         "StudentName" : "Adam"
      },
      {
         "StudentId" : 8,
         "StudentName" : "Larry"
      }
   ]
}

以下是刪除陣列中文件的查詢

> db.deleteDocumentsDemo.update({},
... {$pull: {StudentsDetails: {StudentName: "David"}}},
... {multi: true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })

讓我們檢查一下文件是否被刪除。以下是查詢

> db.deleteDocumentsDemo.find().pretty();

這將產生以下輸出

{
   "_id" : 100,
   "StudentsDetails" : [
      {
         "StudentId" : 1,
         "StudentName" : "John"
      },
      {
         "StudentId" : 2,
         "StudentName" : "Carol"
      },
      {
         "StudentId" : 3,
         "StudentName" : "Sam"
      },
      {
         "StudentId" : 4,
         "StudentName" : "Mike"
      }
   ]
}
{
   "_id" : 200,
   "StudentsDetails" : [
      {
         "StudentId" : 6,
         "StudentName" : "Ramit"
      },
      {
         "StudentId" : 7,
         "StudentName" : "Adam"
      },
      {
         "StudentId" : 8,
         "StudentName" : "Larry"
      }
   ]
}

檢視上面的示例輸出,“StudentId”的值為 5,即“David”的“StudentName”已被刪除。

更新於: 2019-7-30

197 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告