如何更新某些嵌入式文档,例如:
我有对象:
{
"_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;
感谢您的帮助。
答案 0 :(得分:-1)
{ShoppingCartItems.ProductId:4},{$ set:{&#34; ShoppingCartItems。$。AdditionalShippingChargeProduct&#34;:6}}