6

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?

1

1 Answer 1

5

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 });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.