Delete a field and value in MongoDB?


To delete a MongoDB field and value, you can use $unset operator. Let us first create a collection with documents −

> db.deleteFieldDemo.insertOne({"FirstName":"John","LastName":"Smith"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9fb767219729fde21ddad")
}
> db.deleteFieldDemo.insertOne({"FirstName":"David","LastName":"Miller"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9fb837219729fde21ddae")
}
> db.deleteFieldDemo.insertOne({"FirstName":"Carol","LastName":"Taylor"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cb9fb8d7219729fde21ddaf")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cb9fb767219729fde21ddad"),
   "FirstName" : "John",
   "LastName" : "Smith"
}
{
   "_id" : ObjectId("5cb9fb837219729fde21ddae"),
   "FirstName" : "David",
   "LastName" : "Miller"
}
{
   "_id" : ObjectId("5cb9fb8d7219729fde21ddaf"),
   "FirstName" : "Carol",
   "LastName" : "Taylor"
}

Following is the query to delete a field with value −

> db.deleteFieldDemo.update(
...    { FirstName: { $exists: true } },
...    { $unset: { FirstName: 1 } },
...    false,
...    true
... );
WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })

Let us check the field FirstName have been deleted from the collection or not −

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

This will produce the following output −

{ "_id" : ObjectId("5cb9fb767219729fde21ddad"), "LastName" : "Smith" }
{ "_id" : ObjectId("5cb9fb837219729fde21ddae"), "LastName" : "Miller" }
{ "_id" : ObjectId("5cb9fb8d7219729fde21ddaf"), "LastName" : "Taylor" }

Updated on: 30-Jul-2019

371 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements