How to search for a record (field) and then delete it in MongoDB?


To search for a field, use $exists and to delete it, use $unset. The $unset operator in MongoDB deletes a particular field.

Let us create a collection with documents −

> db.demo562.insertOne({"Name":"Chris","Age":21});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8f4ae854b4472ed3e8e872")
}
> db.demo562.insertOne({"Age":20});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8f4ae954b4472ed3e8e873")
}
> db.demo562.insertOne({"Name":"David","Age":23});{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8f4aea54b4472ed3e8e874")
}

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

> db.demo562.find();

This will produce the following output −

{ "_id" : ObjectId("5e8f4ae854b4472ed3e8e872"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e8f4ae954b4472ed3e8e873"), "Age" : 20 }
{ "_id" : ObjectId("5e8f4aea54b4472ed3e8e874"), "Name" : "David", "Age" : 23 }

Following is the query to search for a record and then delete it −

> db.demo562.update( {Name:{$exists:true} },{ $unset: {"Name":""}},{multi:true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

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

> db.demo562.find();

This will produce the following output −

{ "_id" : ObjectId("5e8f4b6654b4472ed3e8e875"), "Age" : 21 }
{ "_id" : ObjectId("5e8f4b6754b4472ed3e8e876"), "Age" : 20 }
{ "_id" : ObjectId("5e8f4b6854b4472ed3e8e877"), "Age" : 23 }

Updated on: 14-May-2020

380 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements