MongoDB 查詢如何從文件中刪除陣列元素?


使用 $pull 可按以下語法從 MongoDB 文件中刪除陣列元素 −

db.yourCollectionName.update( { },{ $pull: { yourFieldName: yourValue }},{multi:true });

讓我們先建立一個包含文件的集合 −

>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["John","Sam","Carol","David"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd90d011a844af18acdffc1")
}
>db.removeArrayElementsDemo.insertOne({"AllPlayerName":["Chris","Robert","John","Mike"]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cd90d2e1a844af18acdffc2")
}

以下查詢可透過 find() 方法顯示某個集合中的所有文件 −

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

這將產生以下輸出 −

{
   "_id" : ObjectId("5cd90d011a844af18acdffc1"),
   "AllPlayerName" : [
      "John",
      "Sam",
      "Carol",
      "David"
   ]
}
{
   "_id" : ObjectId("5cd90d2e1a844af18acdffc2"),
   "AllPlayerName" : [
      "Chris",
      "Robert",
      "John",
      "Mike"
   ]
}

以下查詢可從文件中刪除陣列元素 −

> db.removeArrayElementsDemo.update( { },{ $pull: { AllPlayerName: "John" }},{multi:true });
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

讓我們再次檢查所有文件 −

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

這將產生以下輸出 −

{
   "_id" : ObjectId("5cd90d011a844af18acdffc1"),
   "AllPlayerName" : [
      "Sam",
      "Carol",
      "David"
   ]
}
{
   "_id" : ObjectId("5cd90d2e1a844af18acdffc2"),
   "AllPlayerName" : [
      "Chris",
      "Robert",
      "Mike"
   ]
}

更新日期:30-Jul-2019

180 次瀏覽

開啟您的 職業生涯

完成課程獲取認證

開始
廣告
© . All rights reserved.