Home>Article>Database> Remove array elements from MongoDB collection using update() and $pull

Remove array elements from MongoDB collection using update() and $pull

WBOY
WBOY forward
2023-09-13 16:45:09 1275browse

使用 update() 和 $pull 从 MongoDB 集合中删除数组元素

Let us first create a collection containing documents -

> db.removingAnArrayElementDemo.insertOne({"UserMessage":["Hi","Hello","Bye"]}); { "acknowledged" : true, "insertedId" : ObjectId("5cef97bdef71edecf6a1f6a4") }

Display all the documents in the collection with the help of find() method -

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

Output

{ "_id" : ObjectId("5cef97bdef71edecf6a1f6a4"), "UserMessage" : [ "Hi", "Hello", "Bye" ] }

The following is the query to delete array elements from MongoDB -

> db.removingAnArrayElementDemo.update( {_id:ObjectId("5cef97bdef71edecf6a1f6a4")}, { "$pull": { "UserMessage": "Hello" } } ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let’s check the document again:

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

Output

{ . "_id" : ObjectId("5cef97bdef71edecf6a1f6a4"), "UserMessage" : [ "Hi", "Bye" ] }

The above is the detailed content of Remove array elements from MongoDB collection using update() and $pull. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete