MongoDB - Supprimer un champ du tableau
Avant MongoDB 2.6, il n'y avait pas de fonction officielle pour$unset
un champ du document tableau.
Note
-
$unset is not working with arrays
-
$pull is used to remove the entire record, not a particular field.
1. Documents de tableaux
Dans cet article, nous allons vous montrer comment supprimer le champ «countryName» du tableau ci-dessous.
> db.hosting.findOne(); { "_id" : 39, "domain" : "example.com", "countryStat" : [ { "countryCode" : "us", "countryName" : "United States", "count" : 2170 }, { "countryCode" : "il", "countryName" : "Israel", "count" : 22 }, ] }
2. Supprimer le champ des documents de tableaux
Pour supprimer des champs du tableau, vous devez écrire un script comme celui-ci:
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); });
Sortie
> db.hosting.findOne(); { "_id" : 39, "domain" : "example.com", "countryStat" : [ { "countryCode" : "us", "count" : 2170 }, { "countryCode" : "il", "count" : 22 }, ] }