我正在通过最新的C#驱动程序(当前为v2.7.0)使用MongoDB 4.0。我有一个文档,其中有Options
,而Options
有Inventory
。因此,换句话说,库存清单嵌套在选项阵列中。如何降低库存水平并仅更新库存?
这是我的文档以JSON格式显示的样子:
{
"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"
}
]
}
]
}
如果我知道选项的ID和库存项目的ID,如何使用C#驱动程序在单个选项内更改单个库存项目的名称?
答案 0 :(得分:3)
在MongoDB 4.0中,您可以使用$[<identifier>]
syntax并将ArrayFilters
添加到UpdateOptions
参数:
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);
这将唯一地标识需要在Inventory
内部进行更新的Options
项