使用MongoDB C#驱动程序从所有文档中删除数组元素

鉴于以下内容:

{ "_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": "" } ] } 

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

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

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

更新解决方案:

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

这是代码:

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

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

 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);});