Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to remove document on the basis of _id in MongoDB?
To remove a document based on its _id in MongoDB, use the remove() method with the ObjectId as the matching criteria. Each document has a unique _id field that serves as the primary key.
Syntax
db.collectionName.remove({"_id": ObjectId("yourObjectId")});
Sample Data
Let us first create a collection with sample documents ?
db.removeDocumentOnBasisOfId.insertMany([
{"UserName": "Larry", "UserAge": 23, "UserCountryName": "US"},
{"UserName": "Sam", "UserAge": 21, "UserCountryName": "UK"},
{"UserName": "Chris", "UserAge": 24, "UserCountryName": "US"},
{"UserName": "Robert", "UserAge": 26, "UserCountryName": "UK"},
{"UserName": "David", "UserAge": 28, "UserCountryName": "AUS"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5c986f9f330fd0aa0d2fe4a3"),
ObjectId("5c986fb4330fd0aa0d2fe4a4"),
ObjectId("5c986fc0330fd0aa0d2fe4a5"),
ObjectId("5c986fcf330fd0aa0d2fe4a6"),
ObjectId("5c986fed330fd0aa0d2fe4a7")
]
}
Display All Documents
db.removeDocumentOnBasisOfId.find().pretty();
{
"_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"
}
Example: Remove Document by _id
Remove Chris's document using its _id ?
db.removeDocumentOnBasisOfId.remove({"_id": ObjectId("5c986fc0330fd0aa0d2fe4a5")});
WriteResult({ "nRemoved": 1 })
Verify Result
Check if the document has been removed successfully ?
db.removeDocumentOnBasisOfId.find().pretty();
{
"_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"
}
Conclusion
Use remove({"_id": ObjectId("id")}) to delete a specific document by its unique identifier. The WriteResult confirms successful removal with nRemoved: 1.
Advertisements
