使用 update() 和 $pull 從 MongoDB 集合中移除陣列元素
讓我們首先使用文件建立一個集合 -
> db.removingAnArrayElementDemo.insertOne({"UserMessage":["Hi","Hello","Bye"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cef97bdef71edecf6a1f6a4") }
在集合中使用 find() 方法顯示所有文件 -
> db.removingAnArrayElementDemo.find().pretty();
輸出
{ "_id" : ObjectId("5cef97bdef71edecf6a1f6a4"), "UserMessage" : [ "Hi", "Hello", "Bye" ] }
以下是從 MongoDB 中移除陣列元素的查詢 -
> db.removingAnArrayElementDemo.update( {_id:ObjectId("5cef97bdef71edecf6a1f6a4")}, { "$pull": { "UserMessage": "Hello" } } ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
讓我們重新檢查一下該文件
> db.removingAnArrayElementDemo.find().pretty();
輸出
{ . "_id" : ObjectId("5cef97bdef71edecf6a1f6a4"), "UserMessage" : [ "Hi", "Bye" ] }
廣告