從 MongoDB 集合中刪除陣列元素
若要刪除陣列元素,只需使用 $pull 以及 update()。讓我們使用文件建立一個集合 -
> db.demo146.insertOne({"ListOfEmployeeNames":["Chris","David","Bob","Mike"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e32f54ffdf09dd6d08539bd") }
使用 find() 方法顯示集合中的所有文件 -
> db.demo146.find();
這將產生以下輸出 -
{ "_id" : ObjectId("5e32f54ffdf09dd6d08539bd"), "ListOfEmployeeNames" : [ "Chris", "David", "Bob", "Mike" ] }
以下是從 MongoDB 中刪除陣列元素的查詢 -
> db.demo146.update({}, { "$pull": { "ListOfEmployeeNames": "Bob" } }); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
使用 find() 方法顯示集合中的所有文件 -
> db.demo146.find();
這將產生以下輸出 -
{ "_id" : ObjectId("5e32f54ffdf09dd6d08539bd"), "ListOfEmployeeNames" : [ "Chris", "David", "Mike" ] }
廣告