問題描述
mongodb c#更新嵌入文檔 (mongodb c# update embedded document)
如何更新一些嵌入的文檔,例如:
我有對象:
{
"_id" : ObjectId("5648c70f574b7e15b0a2ddda"),
"Username" : "admin@yourStore.com",
"Email" : "admin@yourStore.com",
"ShoppingCartItems" : [
{
"ProductId" : NumberInt(4),
"AdditionalShippingChargeProduct" : NumberInt(0),
},
{
"ProductId" : NumberInt(4),
"AdditionalShippingChargeProduct" : NumberInt(0),
},
{
"ProductId" : NumberInt(5),
"AdditionalShippingChargeProduct" : NumberInt(0),
},
],
}
我需要更新字段 AdditionalShippingChargeProduct = 5 但僅限其中 ProductId 等於 4。
這段代碼只更新第一個位置,我需要更新所有匹配的位置。
var builder = Builders<Customer>.Filter;
var filter = builder.ElemMatch(x => x.ShoppingCartItems, y => y.ProductId == 4);
var update = Builders<Customer>.Update
.Set("ShoppingCartItems.$.AdditionalShippingChargeProduct", 5);
var result = customer.UpdateManyAsync(filter, update).Result;
感謝您的幫助。
參考解法
(by GrandNode)