MongoDB Remove a field from array
By:Roy.LiuLast updated:2019-08-17
Prior to MongoDB 2.6, there is no official function to $unset a field from array document.
Note
- $unset is not working with arrays
- $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
From:一号门
Previous:Spring Caching and Ehcache example
COMMENTS