You can use $pull operator to remove the object from an array in MongoDB. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −
> db.removeObjectFromArrayDemo.insertOne( ... { ... ... "StudentName": "John", ... "StudentAcademicProjectDetails": ... [{ ... "StudentProjectId": 101, ... "StudentProjectName": "Pig Dice Game" ... }, ... { ... "StudentProjectId": 110, ... "StudentProjectName": "Library Management System" ... }, ... ... { ... "StudentProjectId": 120, ... "StudentProjectName": "Phonebook Management System" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5c8ad13d6cea1f28b7aa0817") }
Display all documents from a collection with the help of find() method. The query is as follows −
> db.removeObjectFromArrayDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"), "StudentName" : "John", "StudentAcademicProjectDetails" : [ { "StudentProjectId" : 101, "StudentProjectName" : "Pig Dice Game" }, { "StudentProjectId" : 110, "StudentProjectName" : "Library Management System" }, { "StudentProjectId" : 120, "StudentProjectName" : "Phonebook Management System" } ] }
Here is the query to remove the object from an array in MongoDB −
> db.removeObjectFromArrayDemo.update( ... {'_id': ObjectId("5c8ad13d6cea1f28b7aa0817")}, ... { $pull: { "StudentAcademicProjectDetails" : { StudentProjectId: 101 } } }, ... false, ... true ... ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Let us check the documents from collection to check the object has been removed from an array or not. The query is as follows −
> db.removeObjectFromArrayDemo.find().pretty();
The following is the output −
{ "_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"), "StudentName" : "John", "StudentAcademicProjectDetails" : [ { "StudentProjectId" : 110, "StudentProjectName" : "Library Management System" }, { "StudentProjectId" : 120, "StudentProjectName" : "Phonebook Management System" } ] }
Look at the above sample output, the field “StudentProjectId” with 101 has been removed.