MongoDB - Entfernen Sie ein Feld aus dem Array
Vor MongoDB 2.6 gibt es keine offizielle Funktion für$unset
ein Feld aus einem Array-Dokument.
Note
-
$unset is not working with arrays
-
$pull is used to remove the entire record, not a particular field.
1. Ordnet Dokumente an
In diesem Artikel zeigen wir Ihnen, wie Sie das Feld "countryName" aus dem unteren Array entfernen.
> db.hosting.findOne(); { "_id" : 39, "domain" : "example.com", "countryStat" : [ { "countryCode" : "us", "countryName" : "United States", "count" : 2170 }, { "countryCode" : "il", "countryName" : "Israel", "count" : 22 }, ] }
2. Feld aus Arrays-Dokumenten entfernen
Um Felder aus dem Array zu entfernen, müssen Sie ein Skript wie das folgende schreiben:
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); });
Ausgabe
> db.hosting.findOne(); { "_id" : 39, "domain" : "example.com", "countryStat" : [ { "countryCode" : "us", "count" : 2170 }, { "countryCode" : "il", "count" : 22 }, ] }