To remove a specific document, use remove() in MongoDB. Let us create a collection with documents −
> db.demo56.insertOne({"Name":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e272e0bcfb11e5c34d89917")
}
> db.demo56.insertOne({"Name":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e272e10cfb11e5c34d89918")
}
> db.demo56.insertOne({"Name":"Bob"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e272e13cfb11e5c34d89919")
}Display all documents from a collection with the help of find() method −
> db.demo56.find();
This will produce the following output −
{ "_id" : ObjectId("5e272e0bcfb11e5c34d89917"), "Name" : "Chris" }
{ "_id" : ObjectId("5e272e10cfb11e5c34d89918"), "Name" : "David" }
{ "_id" : ObjectId("5e272e13cfb11e5c34d89919"), "Name" : "Bob" }Following is the query to remove a specific document −
> db.demo56.remove({_id:ObjectId("5e272e10cfb11e5c34d89918")});
WriteResult({ "nRemoved" : 1 })Display all documents from a collection with the help of find() method −
> db.demo56.find();
This will produce the following output −
{ "_id" : ObjectId("5e272e0bcfb11e5c34d89917"), "Name" : "Chris" }
{ "_id" : ObjectId("5e272e13cfb11e5c34d89919"), "Name" : "Bob" }