I am looking for a way to conditionally combine Set operations. At the moment I have been unable to increment onto the updatedefinitions without having them consecutively dotted one after the other.
eg. instead of:
Builders<BsonDocument>.Update.Set("someElement.Length", b.Length)
.Set("someElement.Path", b.Path)
I am trying to get find a way to use something in the vain of:
var update = Builders<BsonDocument>.Update;
bool hasChanged = false;
if (a.Length != b.Length)
{
hasChanged = true;
update.Set("someElement.Length", b.Length)
}
if (a.Path != b.Path)
{
hasChanged = true;
update.Set("someElement.Path", b.Path)
}
if (hasChanged)
await someCollection.UpdateOneAsync(Builders<someModel>.Filter.Eq("_id", a.Id), update);
Is there a way of doing this or am I chasing a pie in the sky? I dont want to replace the entire document, and am looking to only update fields that have changed.
UpdateDefinition is an immutable object, so chaining operations on them keeps creating a new one each time. To do it conditionally, you need assign the result back to itself, just like LINQ.
update = update.Set(...);
If you maintain a collection of your conditionally created UpdateDefinitions, you can pass that collection into the Combine operator to create your final UpdateDefinition.
You can find an example on this similar question: C# MongoDB Driver - How to use UpdateDefinitionBuilder?
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