C# - MongoDB how to remove an item from multiple nested arrays by element value?

时间秒杀一切 提交于 2019-12-11 07:16:07

问题


I have this JSON structure in a mongo db collection:

{
    "Id":"123",
    "Product": "test",
    "Tags":[
        {
            "Name": "name",
            "Categories": [
                {
                    "Name": "test",
                    "OtherValue": ...
                }
            ]
        },
        {
            "Name": "name",
            "Categories": [
                {
                    "Name": "test",
                    "OtherValue": ...
                }
            ]
        }
    ]
}

Is there a way to be able to remove an item from all of the nested "Categories" arrays by the item's "Name" property?

For example, remove all categories where "Name" == "test"?

I tried something like this:

var filter = Builders<Item>.Filter.Eq(item => item.Id, "123");
var update = Builders<Item>.Update.Pull("Tags.$[].Categories[i]", "test");

var arrayFilters = new List<ArrayFilterDefinition>
{
    new JsonArrayFilterDefinition<Setup>("{\"i.Name\": \"test\"}")
};

var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };
await Collection.UpdateOneAsync(filter, update, updateOptions);

But it didn't work... Any ideas?


回答1:


Try positional all $[] variant.

var filter = Builders<Item>.Filter.Eq(item => item.Id, "123");
var update = Builders<Item>.Update.PullFilter("Tags.$[].Categories", Builders<BsonDocument>.Filter.Eq("Name", "test"));

await Collection.UpdateOneAsync(filter, update);


来源:https://stackoverflow.com/questions/48887667/c-sharp-mongodb-how-to-remove-an-item-from-multiple-nested-arrays-by-element-v

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!