Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 456
Ofer Albersheim Avatar asked Oct 18 '22 05:10

Ofer Albersheim


1 Answers

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 });
like image 118
andrei.ciprian Avatar answered Nov 02 '22 12:11

andrei.ciprian