C#-MongoDB如何通过元素值从多个嵌套数组中删除项目? [英] C# - MongoDB how to remove an item from multiple nested arrays by element value?

查看:86
本文介绍了C#-MongoDB如何通过元素值从多个嵌套数组中删除项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在mongo db集合中具有以下JSON结构:

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

是否可以通过商品的"Name"属性从所有嵌套的类别"数组中删除该商品?

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

例如,删除所有类别,其中"Name" == "test"?

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

我尝试过这样的事情:

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?

推荐答案

尝试

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

这篇关于C#-MongoDB如何通过元素值从多个嵌套数组中删除项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆