使用MongoDB C#驱动程序从所有文档中删除数组元素 [英] Remove array element from ALL documents using MongoDB C# driver
问题描述
给出以下内容:
{
"_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": ""
}
]
}
在代码中,我删除了createdBy属性.现在如何使用C#驱动程序更新(取消设置)我的ENTIRE数据库,从而也删除了createdBy?生成的数据库应如下所示:
In code, I deleted the discoveredBy property. How do I now update (unset) my ENTIRE db using the C# driver so that discoveredBy is also deleted? The resulting db should look like:
{
"_id" : 1,
"name" : "Nature",
"area": [
{
"place": "Some place"
},
{
"place": "Some place 2"
}
],
"_id" : 2,
"name" : "Tropics",
"area": [
{
"place": "Some place"
},
{
"place": "Some place 2"
}
]
}
当前,在我更改代码后尝试执行查找"时,此操作失败,因为DiscoverBy属性不再存在于代码中,并且序列化过程无法找到存储仍存在于db中的已删除属性的位置.因此,需要从数据库中完全删除该字段.
Currently when trying to perform a Find after my code change, it's failing because the discoveredBy property is no longer in code and the serialization processes can't find a place to store the removed property which still exists in the db. Hence the need to delete that field from the db in its entirety.
已更新解决方案:
感谢所有输入专家,但这并不是重复的,因为当我尝试使用新驱动程序在C#中运行时,我尝试过的一切似乎都已被弃用.无论哪种方式,这都是我最终确定的解决方案.这里的键是使用"$ []" ,根据MongoDB,它是3.6版以来的新功能.请参见 https://docs.mongodb. com/manual/reference/operator/update/positional-all/#up. S [] 了解更多信息.
Thanks for all the input guys but this isn't a duplicate as everything I tried seemed to be deprecated when I tried running in C# with the new driver. Either way, here's the fix I eventually settled on. The key here is using "$[]" which according to MongoDB is new as of version 3.6. See https://docs.mongodb.com/manual/reference/operator/update/positional-all/#up.S[] for more information.
代码如下:
{
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});
}
推荐答案
在您的情况下,请执行以下操作:
In your case do something like this:
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);});
这篇关于使用MongoDB C#驱动程序从所有文档中删除数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!