Ofer Albersheim
Ofer Albersheim

Reputation: 91

mongodb C# Driver update multiple fields

I have a dictionary that I'd like to use to update a mongodb record. I'm using a simple foreach to iterate the dictionary and construct an UpdateDefinition object. The problem is that I can't initialize an empty UpdateDefinition object, and therefore am forced into initializing the UpdateDefinition with an existing key value:

IDictionary<string, object> document = GetDocument();
string firstKey = document.Keys.First();
var update = Builders<BsonDocument>.Update.Set(firstKey, document[firstKey]);

foreach (var key in document.Keys)
{
    update = update.Set(key, document[key]);
}

This is horrible. FilterDefinition has an empty Filter which works great for this purpose. Is there anything similar for building iterative UpdateDefinitions?

Upvotes: 6

Views: 5605

Answers (1)

andrei.ciprian
andrei.ciprian

Reputation: 3025

Using clues:

  1. BsonDocument has a constructor with a Dictionary parameter
  2. There's an implicit conversion from BsonDocument to UpdateDefinition
  3. There's an implicit conversion from BsonDocument to FilterDefinition

you can do reduce everything to this one liner, (upsert not mandatory):

// IDictionary<string, object> dict = ...;
collection.UpdateOne(new BsonDocument("_id", "some_filter"), new BsonDocument("$set", new BsonDocument(dict)), new UpdateOptions { IsUpsert = true });

Upvotes: 5

Related Questions