Remove only one document in MongoDB?


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

> db.removeOnlyOneDocumentDemo.insertOne({"FirstName":"John","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc6ca2f9cb58ca2b005e674")
}
> db.removeOnlyOneDocumentDemo.insertOne({"FirstName":"Carol","LastName":"Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc6ca399cb58ca2b005e675")
}
> db.removeOnlyOneDocumentDemo.insertOne({"FirstName":"David","LastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc6ca429cb58ca2b005e676")
}

Following is the query to display all documents from a collection with the help of find() method −

> db.removeOnlyOneDocumentDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc6ca2f9cb58ca2b005e674"),
   "FirstName" : "John",
   "LastName" : "Smith"
}
{
   "_id" : ObjectId("5cc6ca399cb58ca2b005e675"),
   "FirstName" : "Carol",
   "LastName" : "Taylor"
}
{
   "_id" : ObjectId("5cc6ca429cb58ca2b005e676"),
   "FirstName" : "David",
   "LastName" : "Miller"
}

Following is the query to remove only one document in MongoDB. Here we are removing a document with “FirstName” David −

> var documentValue = db.removeOnlyOneDocumentDemo.findOne({'FirstName':'David'});
> db.removeOnlyOneDocumentDemo.remove({_id:documentValue._id});
WriteResult({ "nRemoved" : 1 })

Let us check one document has been removed from the collection or not −

> db.removeOnlyOneDocumentDemo.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5cc6ca2f9cb58ca2b005e674"),
   "FirstName" : "John",
   "LastName" : "Smith"
}
{
   "_id" : ObjectId("5cc6ca399cb58ca2b005e675"),
   "FirstName" : "Carol",
   "LastName" : "Taylor"
}

Updated on: 30-Jul-2019

75 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements