mongodb c#更新嵌入文檔 (mongodb c# update embedded document)


問題描述

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)

參考文件

  1. mongodb c# update embedded document (CC BY‑SA 2.5/3.0/4.0)

#mongoDB #C#






相關問題

將 (.net) BsonDocument 字符串轉換為 (java) DBObject (Converting (.net) BsonDocument string into a (java) DBObject)

Mongo 客戶端出錯 (Error with Mongo Client)

對列表進行排序並在 mongodb 中插入一個新列 (Sort the list and insert a new column in mongodb)

無法導入示例數據集(系統找不到指定文件) (Cannot import example dataset (the system cannot find the specified file))

mongodb c#更新嵌入文檔 (mongodb c# update embedded document)

查詢嵌入列表中的數組 (Querying for array in embedded list)

搜索條件的mongodb map reduce (mongodb map reduce for search criteria)

org.bson.codecs.configuration.CodecConfigurationException:找不到類 [Ljava.lang.String; 的編解碼器; (org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class [Ljava.lang.String;)

在碼頭上部署 gwt Web 應用程序 (deploying gwt web application on jetty)

MongoMetaRecord MegaProtoUser 登錄時密碼未散列 (MongoMetaRecord MegaProtoUser Password not hashed when signing in)

將 mongo shell 連接到受限的 MongoDB Atlas 數據庫? (Connect mongo shell to restricted MongoDB Atlas Database?)

用於 $or 和 $and 場景的 $elemMatch 數組 (Arrays working $elemMatch for $or and $and scenarios)







留言討論