如何从嵌套在数组中的数组更新项目 [英] How to update item from array nested within array

查看:50
本文介绍了如何从嵌套在数组中的数组更新项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过最新的C#驱动程序(当前为v2.7.0)使用MongoDB 4.0.我有一个文档,其中OptionsOptions具有Inventory.因此,换句话说,库存清单嵌套在一组期权中.如何降低到库存水平并仅更新库存?

I'm using MongoDB 4.0 via the latest C# driver (v2.7.0 at this time). I have a document which has Options and Options have Inventory. So in other words, an array of inventory is nested within an array of options. How do I get down to the inventory level and update the inventory only?

这是我的文档以JSON形式显示的样子:

Here's what my document looks like in JSON form:

{
  "Options": [
    {
      "Id": 1,
      "Description": "This is one option",
      "Inventory": [
        {
          "Id": 1,
          "Name": "Box of stuff"
        },
        {
          "Id": 2,
          "Name": "Another box of stuff"
        }
      ]
    },
    {
      "Id": 2,
      "Description": "This a second option",
      "Inventory": [
        {
          "Id": 1,
          "Name": "Box of stuff"
        },
        {
          "Id": 2,
          "Name": "Another box of stuff"
        }
      ]
    }
  ]
}

使用C#驱动程序,如果我知道选项的ID和库存项目的ID,如何在单个选项内更改单个库存项目的名称?

Using the C# driver, how do I change the name of a single inventory item within a single option, if I know the Id of the option and the Id of the inventory item?

推荐答案

在MongoDB 4.0中,您可以使用$[<identifier>]

In MongoDB 4.0 you can use the $[<identifier>] syntax and add ArrayFilters to UpdateOptions parameter:

var filter = Builders<Model>.Filter.Empty;
var update = Builders<Model>.Update.Set("Options.$[option].Inventory.$[inventory].Name", "New name");

var arrayFilters = new List<ArrayFilterDefinition>();
ArrayFilterDefinition<BsonDocument> optionsFilter = new BsonDocument("option.Id", new BsonDocument("$eq", optionId));
ArrayFilterDefinition<BsonDocument> inventoryFilter = new BsonDocument("inventory.Id", new BsonDocument("$eq", inventoryId));
arrayFilters.Add(optionsFilter);
arrayFilters.Add(inventoryFilter);

var updateOptions = new UpdateOptions { ArrayFilters = arrayFilters };

var result = DefaultCollection.UpdateOne(filter, update, updateOptions);

这将唯一地标识需要在Options

That will uniquely identify Inventory item that needs to be updated inside Options

这篇关于如何从嵌套在数组中的数组更新项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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