How to remove key fields in MongoDB?


To remove key fields in MongoFB, you can use $unset operator. Let us first create a collection with documents −

>db.removeKeyFieldsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe","StudentAge":23});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc6c8289cb58ca2b005e672")
}
>db.removeKeyFieldsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cc6c8359cb58ca2b005e673")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5cc6c8289cb58ca2b005e672"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Doe",
   "StudentAge" : 23
}
{
   "_id" : ObjectId("5cc6c8359cb58ca2b005e673"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Smith",
   "StudentAge" : 21
}

Following is the query to remove key fields. Here, we are removing the StudentAge −

> db.removeKeyFieldsDemo.updateMany({},{$unset:{StudentAge:1}});
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }

Let us display all documents from the above collection −

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

This will produce the following output −

{
   "_id" : ObjectId("5cc6c8289cb58ca2b005e672"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Doe"
}
{
   "_id" : ObjectId("5cc6c8359cb58ca2b005e673"),
   "StudentFirstName" : "John",
   "StudentLastName" : "Smith"
}

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements