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