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?
Using clues:
BsonDocument
has a constructor with a Dictionary
parameterBsonDocument
to UpdateDefinition
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With