Remove only a single document in MongoDB


To remove only a single document in MongoDB, use remove(). Let us create a collection with documents −

> db.demo165.insertOne({"ClientId":101,"ClientName":"Chris","ClientAge":34});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36895c9e4f06af551997cc")
}
> db.demo165.insertOne({"ClientId":102,"ClientName":"Bob","ClientAge":32});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e3689659e4f06af551997cd")
}
> db.demo165.insertOne({"ClientId":103,"ClientName":"David","ClientAge":35});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e36896d9e4f06af551997ce")
}

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

> db.demo165.find();

This will produce the following output −

{ "_id" : ObjectId("5e36895c9e4f06af551997cc"), "ClientId" : 101, "ClientName" : "Chris", "ClientAge" : 34 }
{ "_id" : ObjectId("5e3689659e4f06af551997cd"), "ClientId" : 102, "ClientName" : "Bob", "ClientAge" : 32 }
{ "_id" : ObjectId("5e36896d9e4f06af551997ce"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }

Following is the query to remove document from MongoDB −

> db.demo165.remove({"ClientId":102});
WriteResult({ "nRemoved" : 1 })

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

> db.demo165.find();

This will produce the following output −

{ "_id" : ObjectId("5e36895c9e4f06af551997cc"), "ClientId" : 101, "ClientName" : "Chris", "ClientAge" : 34 }
{ "_id" : ObjectId("5e36896d9e4f06af551997ce"), "ClientId" : 103, "ClientName" : "David", "ClientAge" : 35 }

Updated on: 01-Apr-2020

77 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements