MongoDB - удалить поле из массива
До MongoDB 2.6 не было официальной функции для$unset
поля из документа массива.
Note
-
$unset is not working with arrays
-
$pull is used to remove the entire record, not a particular field.
1. Массивы Документы
В этой статье мы покажем вам, как удалить поле «countryName» из массива ниже.
> db.hosting.findOne(); { "_id" : 39, "domain" : "example.com", "countryStat" : [ { "countryCode" : "us", "countryName" : "United States", "count" : 2170 }, { "countryCode" : "il", "countryName" : "Israel", "count" : 22 }, ] }
2. Удалить поле из массивов документов
Чтобы удалить поля из массива, вам нужно написать такой скрипт:
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); });
Выход
> db.hosting.findOne(); { "_id" : 39, "domain" : "example.com", "countryStat" : [ { "countryCode" : "us", "count" : 2170 }, { "countryCode" : "il", "count" : 22 }, ] }