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();
{ "_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();
{ . "_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!