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

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
2 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
2 Comment authors
satya prasadPratik Burkhawala Recent comment authors
newest oldest most voted
satya prasad
Guest
satya prasad

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

Pratik Burkhawala
Guest
Pratik Burkhawala

How to remove the whole doc in array