3

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?

2
  • What MongoDB version ? Commented Jul 31, 2018 at 20:36
  • I am using MongoDB 4.0. Updated question. Commented Jul 31, 2018 at 20:37

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.