2
据我所知,mongodb知道Dictionary
作为一个对象,并且它不能执行任何与数组有关的操作。我改变了序列化并尝试了各种类型的字典序列化。但没有机会。
所以我加载我的领域(字典)(全部)到内存中,更新它并将其设置回mongodb。
有没有什么办法来upsert在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;
}
}
}
它的工作原理。真正好点的人。让看看是否有任何建议,以避免多连接(更新)。到目前为止,这是我接受的答案。 – Soren
我已经更新了答案,这个执行更新只是一次:) –
工作就像一个魅力。感谢您的时间和考虑。 – Soren