To remove document on the basis of _id in MongoDB, implement the following syntax
db.yourCollectionName.remove({“_id”:ObjectId(“yourId”});
Let us first implement the following query to create a collection with documents
>db.removeDocumentOnBasisOfId.insertOne({"UserName":"Larry","UserAge":23,"UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986f9f330fd0aa0d2fe4a3") } >db.removeDocumentOnBasisOfId.insertOne({"UserName":"Sam","UserAge":21,"UserCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986fb4330fd0aa0d2fe4a4") } >db.removeDocumentOnBasisOfId.insertOne({"UserName":"Chris","UserAge":24,"UserCountryName":"US"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986fc0330fd0aa0d2fe4a5") } >db.removeDocumentOnBasisOfId.insertOne({"UserName":"Robert","UserAge":26,"UserCountryName":"UK"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986fcf330fd0aa0d2fe4a6") } >db.removeDocumentOnBasisOfId.insertOne({"UserName":"David","UserAge":28,"UserCountryName":"AUS"}); { "acknowledged" : true, "insertedId" : ObjectId("5c986fed330fd0aa0d2fe4a7") }
Following is the query to display all documents from a collection with the help of find() method
> db.removeDocumentOnBasisOfId.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c986f9f330fd0aa0d2fe4a3"), "UserName" : "Larry", "UserAge" : 23, "UserCountryName" : "US" } { "_id" : ObjectId("5c986fb4330fd0aa0d2fe4a4"), "UserName" : "Sam", "UserAge" : 21, "UserCountryName" : "UK" } { "_id" : ObjectId("5c986fc0330fd0aa0d2fe4a5"), "UserName" : "Chris", "UserAge" : 24, "UserCountryName" : "US" } { "_id" : ObjectId("5c986fcf330fd0aa0d2fe4a6"), "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "UK" } { "_id" : ObjectId("5c986fed330fd0aa0d2fe4a7"), "UserName" : "David", "UserAge" : 28, "UserCountryName" : "AUS" }
Following is the query to remove document on the basis of _id
> db.removeDocumentOnBasisOfId.remove({"_id":ObjectId("5c986fc0330fd0aa0d2fe4a5")}); WriteResult({ "nRemoved" : 1 })
We have removed the records of Chris on the basis of its _id above. Now display all documents from the collection to check the document has been removed or not
> db.removeDocumentOnBasisOfId.find().pretty();
This will produce the following output
{ "_id" : ObjectId("5c986f9f330fd0aa0d2fe4a3"), "UserName" : "Larry", "UserAge" : 23, "UserCountryName" : "US" } { "_id" : ObjectId("5c986fb4330fd0aa0d2fe4a4"), "UserName" : "Sam", "UserAge" : 21, "UserCountryName" : "UK" } { "_id" : ObjectId("5c986fcf330fd0aa0d2fe4a6"), "UserName" : "Robert", "UserAge" : 26, "UserCountryName" : "UK" } { "_id" : ObjectId("5c986fed330fd0aa0d2fe4a7"), "UserName" : "David", "UserAge" : 28, "UserCountryName" : "AUS" }