2017-02-23 82 views
-1

我有一個字典,我想做一個upsert,但我發現的唯一方法是用.Set包裝它到一個字段中,有沒有方法可以將每個字典條目轉換爲字段?在沒有包裝的Mongo Update上使用Dictionary?

var data = new Dictionary<string, object>() { { "Test1", 1 }, { "Test2", 2 } }; 

var filter = Builders<BsonDocument>.Filter.Eq("_id", LoggerScope.Identifier); 
var update = Builders<BsonDocument>.Update 
    .Set() // 
    .SetOnInsert("InsertDate", DateTime.UtcNow); 
var options = new UpdateOptions { IsUpsert = true }; 

await _Collection.UpdateOneAsync(filter, update, options); 

回答

0

我創造了這個擴展方法來完成這項工作:

public static UpdateDefinition<TDocument> SetDictionary<TDocument, TKey, TValue>(this UpdateDefinition<TDocument> update, IDictionary<TKey, TValue> dict) 
    { 
     foreach (var field in dict) 
     { 
      update = update.Set(field.Key as String, field.Value); 
     } 

     return update; 
    } 
相關問題