MongoDB - 配列からフィールドを削除する

MongoDB –配列からフィールドを削除する

MongoDB 2.6より前は、配列ドキュメントのフィールドを$unsetする公式関数はありません。

Note

  1. $unset is not working with arrays

  2. $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
         },

      ]
}