Search code examples
c#mongodbmongodb-.net-driver

Use Dictionary on Mongo Update without wrapper?


I have a dictionary and I want to do an upsert but the only way I found is wrapping it into a field with .Set, Is there a way that each dictionary entry is converted to a field?

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);

Solution

  • I created this extension method to do the job:

        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;
        }