我正在尝试仅更新.Net应用程序上的几个嵌套文档,但我不知道该怎么做。
这是我提出这个问题后一直在寻找的主题之一:
C# - MongoDB - Update an element inside a Nested Document
**数据库对象:**
{
"_id" : ObjectId("5d03a6f5fba276260c4911bd"),
"costumerId" : ObjectId("5c050cdefba2771eac58c84b"),
"order" : 106376,
"items" : [
{
"itemId" : 10226905,
"date" : ISODate("2018-11-30T14:00:00.000Z"),
"description" : "itemA",
"new" : true,
},
{
"itemId" : 10226906,
"date" : ISODate("2018-11-30T14:00:00.000Z"),
"description" : "itemB",
"new" : true,
},
{
"itemId" : 10226907,
"date" : ISODate("2018-11-23T14:00:00.000Z"),
"description" : "ItemC",
"new" : true,
},
{
"itemId" : 10226908,
"date" : ISODate("2018-11-23T14:00:00.000Z"),
"description" : "ItemD",
"new" : false,
},
]
}
MongoDB更新查询:
db.CostumerProducts.update(
{costumerId: 106376},
{
$set:{'items.$[element].new': true}
},
{
multi:true,
arrayFilters: [
{
'element.itemId':{
$in:[10226905,10226906,10226907]
}
}]
})
使用MongoDB驱动程序进行C#更新查询:
var arrayObjects = List<int>{10226905,10226906,10226907};
var filter = Builders<CostumerProductsObject>.Filter.And(new[]
{
new FilterDefinitionBuilder<CostumerProductsObject>().Eq(p=>p.costumerId, costumerId),
new FilterDefinitionBuilder<CostumerProductsObject>().Eq(p=>p.order, order),
});
var set = Builders<ItemsObject>.Update.Set("items.$[element].new", true);
var arrayFilter = new FilterDefinitionBuilder<ItemsObject>().In(a=>a.itemId, itemsArray);
using (var db = new MongoContextInfra())
{
db.Set<CostumerProductsObject>(CollectionName).UpdateMany(filter,
set,
new UpdateOptions
{
ArrayFilters = null
});
}
我希望仅将这三个项目更新为“ arrayObjects”变量。
您能给我看一些代码还是帮我解决我的问题,以便我进行此更新? 谢谢。