MongoDB中的Upsert字典 [英] Upsert Dictionary in MongoDb

查看:0
本文介绍了MongoDB中的Upsert字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,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});
}

注意,这只会添加新的键/值或更新现有的键/值,不会删除任何内容。

这篇关于MongoDB中的Upsert字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆