MongoDB – Remove a field from array

Prior to MongoDB 2.6, there is no official function to $unset a field from array document.

Note

  1. $unset is not working with arrays
  2. $pull is used to remove the entire record, not a particular field.

1. Arrays Documents

In this article, we will show you how to remove the field “countryName” from below array.


> db.hosting.findOne();
{
      "_id" : 39,
      "domain" : "mkyong.com",
      "countryStat" : [
         {
                 "countryCode" : "us",
                 "countryName" : "United States",
                 "count" : 2170
         },
         {
                 "countryCode" : "il",
                 "countryName" : "Israel",
                 "count" : 22
         },
         
      ]
}

2. Remove field from Arrays Documents

To remove fields from array, you need to write a script like this :


db.hosting.find({_id: 39 }).forEach(function(doc) {

	var countries = doc.countryStat;
	for(var i = 0; i < countries.length; ++i) { 
		var x = countries[i];
		delete (x["countryName"]);
		
	}
	db.hosting.save(doc);
});

Output


> db.hosting.findOne();
{
      "_id" : 39,
      "domain" : "mkyong.com",
      "countryStat" : [
         {
                 "countryCode" : "us",
                 "count" : 2170
         },
         {
                 "countryCode" : "il",
                 "count" : 22
         },
         
      ]
}

References

  1. MongoDB $pull documentation
  2. JIRA : Use positional operator to update all items in an array

mkyong

Founder of Mkyong.com, passionate Java and open-source technologies. If you enjoy my tutorials, consider making a donation to these charities.

2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
satya prasad
7 years ago

Can you please suggest, How to delete only “countryName” : “Israel” and Not the “countryName” : “United Statesl”

Pratik Burkhawala
8 years ago

How to remove the whole doc in array