Unset an attribute from a single array element in MongoDB?


Use $unset operator to unset an attribute. Let us first create a collection with documents −

> db.unsetAnAttributeDemo.insertOne(
...    {
...       _id: 1,
...       "StudentDetails": [
...          {
...             "StudentFirstName": "Ramit",
...             "StudentCountryName":"UK"
...          },
...          {
...             "StudentFirstName": "Bob",
...             "StudentCountryName":"US"
...          },
...          {
...             "StudentFirstName": "Carol",
...             "StudentCountryName":"AUS"
...
...          }
...       ]
...    }
... );
{ "acknowledged" : true, "insertedId" : 1 }

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

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

This will produce the following output −

{
   "_id" : 1,
   "StudentDetails" : [
      {
         "StudentFirstName" : "Ramit",
         "StudentCountryName" : "UK"
      },
      {
         "StudentFirstName" : "Bob",
         "StudentCountryName" : "US"
      },
      {
         "StudentFirstName" : "Carol",
         "StudentCountryName" : "AUS"
      }
   ]
}

Following is the query to unset an attribute from a single array element. The attribute “StudentCountryName” with value “AUS” will unset −

> db.unsetAnAttributeDemo.update({"StudentDetails.StudentCountryName": "AUS"}, {$unset:
   {"StudentDetails.$.StudentCountryName": 1}});
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us display the document from the collection to check that attribute StudentCountryName with value “AUS” has been cleared or not −

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

This will produce the following output −

{
   "_id" : 1,
   "StudentDetails" : [
      {
         "StudentFirstName" : "Ramit",
         "StudentCountryName" : "UK"
      },
      {
         "StudentFirstName" : "Bob",
         "StudentCountryName" : "US"
      },
      {
         "StudentFirstName" : "Carol"
      }
   ]
}

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

84 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements