我通过最新的C#驱动程序使用MongoDB 4.0 (现在是v2.7.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"
}
]
}
]
}
使用C#驱动程序,如果我知道选项的Id和库存项目的Id,如何更改单个选项中的单个库存项目的名称?
发布于 2018-08-01 05:03:33
在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);
,它将唯一标识需要在Options
中更新的Inventory
项
https://stackoverflow.com/questions/51621667
复制相似问题