【问题标题】:Remove array element from ALL documents using MongoDB C# driver [duplicate]使用 MongoDB C# 驱动程序从所有文档中删除数组元素 [重复]
【发布时间】:2018-11-14 11:13:56
【问题描述】:

鉴于以下情况:

{
    "_id" : 1,
    "name" : "Nature",
    "area": [
        {
            "place": "Some place",
            "discoveredBy": ""
        },
        {
            "place": "Some place 2",
            "discoveredBy": ""
        }
    ],
    "_id" : 2,
    "name" : "Tropics",
    "area": [
        {
            "place": "Some place",
            "discoveredBy": ""
        },
        {
            "place": "Some place 2",
            "discoveredBy": ""
        }
    ]
}

在代码中,我删除了 foundBy 属性。我现在如何使用 C# 驱动程序更新(取消设置)我的 ENTIRE db,以便同时删除 foundBy?生成的数据库应如下所示:

{
    "_id" : 1,
    "name" : "Nature",
    "area": [
        {
            "place": "Some place"
        },
        {
            "place": "Some place 2"
        }
    ],
    "_id" : 2,
    "name" : "Tropics",
    "area": [
        {
            "place": "Some place"
        },
        {
            "place": "Some place 2"
        }
    ]
}

目前,在我的代码更改后尝试执行 Find 时,它失败了,因为 foundBy 属性不再在代码中,并且序列化过程找不到存储已删除属性的位置,该属性仍然存在于 db 中。因此需要从整个数据库中删除该字段。

已更新解决方案:

感谢所有输入人员,但这不是重复的,因为当我尝试在 C# 中使用新驱动程序运行时,我尝试的所有内容似乎都已被弃用。无论哪种方式,这都是我最终确定的解决方案。这里的关键是使用 "$[]",根据 MongoDB,它是 3.6 版的新功能。请参阅https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up.S[] 了解更多信息。

代码如下:

{
   var filter = Builders<Scene>.Filter.Where(i => i.ID != null);
   var update = Builders<Scene>.Update.Unset("area.$[].discoveredBy");
   var result = collection.UpdateMany(filter, update, new UpdateOptions { IsUpsert = true});
}

【问题讨论】:

  • 如果您发现副本中没有给出解决方案,您应该将其添加到那里。
  • @DourHighArch 完成

标签: c# mongodb driver


【解决方案1】:

在你的情况下做这样的事情:

db.collectionname.find({}).forEach(function(item) {
var ar = item.area;
for(var i = 0; i < ar.length; ++i) { 
    var x = ar[i];
    delete (x["discoveredBy"]);

}
db.collectionname.save(item);});

【讨论】:

  • 这可能是 C# 的过时示例吗?例如,最新的驱动程序似乎不推荐使用 save ,并且找不到 delete 的地方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-21
  • 1970-01-01
  • 2020-05-08
  • 2014-08-18
  • 1970-01-01
  • 2013-11-25
相关资源
最近更新 更多