How to delete a document in MongoDB?

MongoDBDatabaseBig Data Analytics

To delete a document, use remove(). Let us create a collection with documents −

> db.demo79.insertOne({"Name":"Chris"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bdb2271bf0181ecc42293")
}
> db.demo79.insertOne({"Name":"David"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bdb2671bf0181ecc42294")
}
> db.demo79.insertOne({"Name":"Bob"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bdb2971bf0181ecc42295")
}
> db.demo79.insertOne({"Name":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e2bdb2c71bf0181ecc42296")
}

Display all documents from a collection with the help of find() method −

> db.demo79.find();

This will produce the following output −

{ "_id" : ObjectId("5e2bdb2271bf0181ecc42293"), "Name" : "Chris" }
{ "_id" : ObjectId("5e2bdb2671bf0181ecc42294"), "Name" : "David" }
{ "_id" : ObjectId("5e2bdb2971bf0181ecc42295"), "Name" : "Bob" }
{ "_id" : ObjectId("5e2bdb2c71bf0181ecc42296"), "Name" : "Mike" }

Following is the query to delete a document in MongoDB −

> db.demo79.remove({"Name":"Bob"});
WriteResult({ "nRemoved" : 1 })

Display all documents from a collection with the help of find() method −

> db.demo79.find();

This will produce the following output. We deleted a document successfully −

{ "_id" : ObjectId("5e2bdb2271bf0181ecc42293"), "Name" : "Chris" }
{ "_id" : ObjectId("5e2bdb2671bf0181ecc42294"), "Name" : "David" }
{ "_id" : ObjectId("5e2bdb2c71bf0181ecc42296"), "Name" : "Mike" }
raja
Published on 30-Mar-2020 11:47:22
Advertisements