MongoDB – Remove a field from array
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
},
]
}
Can you please suggest, How to delete only “countryName” : “Israel” and Not the “countryName” : “United Statesl”
How to remove the whole doc in array