C# MongoDB - 如何向多个嵌套数组元素添加和删除项目?

C# MongoDB - How to add and remove item to multiple nested array elements?

我在 MongoDB 中有一个文件看起来像这样:

{
    "Id":"123",
    "Product": "test",
    "Tags":[
        {
            "Name": "name",
            "Categories": [
                {
                    //item
                },
                {
                    //item
                }
            ]
        },
        {
            "Name": "name",
            "Categories": [
                {
                    //item
                },
                {
                    //item
                }
            ]
        }
    ]
}

现在,我需要添加一个新的 Item,并且需要将其添加到 ProductTags 元素的所有类别中,方法是 Id. 例如,当我插入 Item 3 时,文档应如下所示:

{
    "Id":"123",
    "Product": "test",
    "Tags":[
        {
            "Name": "name",
            "Categories": [
                {
                    //item 1
                },
                {
                    //item 2
                },
                {
                    //item 3
                }
            ]
        },
        {
            "Name": "name",
            "Categories": [
                {
                    //item 1
                },
                {
                    //item 2
                },
                {
                    //item 3
                }
            ]
        }
    ]
}

删除项目也是如此,它也需要从所有类别中删除。 有没有一种方法可以使用 C# MongoDB 驱动程序来做到这一点,而无需拉出对象并 "manually" 更新它们?

您可以在 3.6 版本的 2.5 驱动程序中尝试如下操作。

查找具有 filter 条件和 update 的文档,其中包含新的 positional identifier 以在 UpdateOne 方法中更新数组中的多个元素。

$[] 更新所有 Tags 数组以在所有 Categories 数组中包含新项目。它充当更新数组中所有元素的占位符。

推送

var filter = Builders<Product>.Filter.Eq("Id", "123");
var update = Builders<Product>.Update.Push("Tags.$[].Categories", "Item 3");
var result = collection.UpdateOne(filter, update);

var filter = Builders<Product>.Filter.Eq("Id", "123");
var update = Builders<Product>.Update.Pull("Tags.$[].Categories", "Item 3");
var result = collection.UpdateOne(filter, update);

附加信息:

您可以在 UpdateOptions 中设置 ArrayFilters 选项,以便在嵌套数组上应用查询条件来控制要更新的元素。

例如更新标签数组中的所有类别,其中每个标签都有 Name 个名称。

var filter = Builders<Product>.Filter.Eq("Id", "123");
var update = Builders<Product>.Update.Push("Tags.$[t].Categories", "Item 3");
var arrayFilters = new List<ArrayFilterDefinition>{ new ArrayFilterDefinition(new BsonDocument("t.Name", "name")) };
var updateOptions = new UpdateOptions({ArrayFilters = arrayFilters});
var result = collection.UpdateOne(filter, update, updateOptions);