据我所知,mongodb知道Dictionary
作为一个对象,它不能做任何与数组相关的操作。我更改了序列化并尝试了各种类型的字典序列化。但是没有机会。
所以我将我的字段(字典)(整个)加载到内存中,更新它并将其设置回mongodb
有没有办法用c#驱动程序在mongodb中 upsert 字典?
我的文档类型:
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;
}
}
}
答案 0 :(得分:1)
您可以浏览要更新/插入的所有属性,并为每个属性执行此操作:
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});
}
请注意,这只是添加新的键/值或更新现有的,这不会删除任何内容。