Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update item from array nested within array

Tags:

c#

mongodb

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?

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

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?

like image 359
Targaryen Avatar asked Jul 01 '26 09:07

Targaryen


1 Answers

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

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

like image 127
mickl Avatar answered Jul 03 '26 00:07

mickl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!