如何更新某些嵌入式文档,例如:

我有对象:

{
    "_id" : ObjectId("5648c70f574b7e15b0a2ddda"),
    "Username" : "[email protected]",
    "Email" : "[email protected]",
    "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;


谢谢你的帮助。

最佳答案

{ShoppingCartItems.ProductId:4},{$ set:{“ ShoppingCartItems。$。AdditionalShippingChargeProduct”:6}}

09-25 18:55