簡體   English   中英

MongoDb 中的 Upsert 字典

[英]Upsert Dictionary in MongoDb

據我所知,mongodb 知道Dictionary作為一個對象,它不能做任何與數組相關的操作。 我更改了序列化並嘗試了各種類型的字典序列化。 但沒有機會了。
所以我將我的字段(字典)(全部)加載到內存中,更新它並將其設置回 mongodb。
有什么方法可以使用 c# 驅動程序在 mongodb 中更新字典嗎?


我的文件類型:

public class Site
    {
        public string Id { get; set; }
        //[BsonDictionaryOptions(DictionaryRepresentation.ArrayOfDocuments)]
        public Dictionary<string,string> Properties { get; set; }
    }

我的更新操作:

public ServiceResult UpdateProperties(string id, Dictionary<string,string> properties)
        {
            var baseList = Collection.Find(m => m.Id == id)
                .Project(s => s.Properties)
                .FirstOrDefault();

            if (baseList == null)
            {
                baseList = properties;
            }
            else
            {
                baseList.Upsert(properties); //update,insert dic by new one
            }

            var filter = Builders<Site>.Filter
                .Eq(m => m.Id, id);

            var update = Builders<Site>.Update
                .Set(m => m.Properties, baseList);

            try
            {
                Collection.UpdateOne(filter, update);

                return ServiceResult.Okay(Messages.ItemUpdated);

            }
            catch (Exception ex)
            {
                return ServiceResult.Exception(ex);
            }    
        }

我非常感謝您能提供的任何幫助。


消歧:

public static class DictionaryExtensions
    {
        public static void Upsert<TKey, TValue>(this Dictionary<TKey, TValue> source, 
                                          Dictionary<TKey, TValue> newOne)
        {
            foreach (var item in newOne)
            {
                source[item.Key] = item.Value;
            }
        }
    }

您可以查看要更新/插入的所有屬性並為每個屬性執行此操作:

UpdateDefinition<Site> upsert = null;
if (properties.Any())
{
    var firstprop = properties.First();
    upsert = Builders<Site>.Update.Set(nameof(Site.Properties) + "." + firstprop.Key, 
                               firstprop.Value);

    foreach (var updateVal in properties.Skip(1))
    {
        upsert = upsert.Set(nameof(Site.Properties) + "." + updateVal.Key, 
                                          updateVal.Value);
    }

    collection.UpdateOne(r => r.Id == "YourId", upsert, 
                                               new UpdateOptions { IsUpsert = true });
}

以前版本的答案,有多個更新:

foreach (var updateVal in properties)
{
    collection.UpdateOne(r => r.Id == "YourId", 
        Builders<Site>.Update.Set( nameof(Site.Properties)+ "." + updateVal.Key, 
                                   updateVal.Value), 
                                   new UpdateOptions { IsUpsert = true});
}

請注意,這只會添加新的鍵/值或更新現有的,這不會刪除任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM