Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb c# combining set operations conditionally

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.

like image 587
xxdefaultxx Avatar asked Mar 08 '16 10:03

xxdefaultxx


Video Answer


2 Answers

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(...);

like image 153
Craig Wilson Avatar answered Nov 07 '22 13:11

Craig Wilson


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?

like image 44
mrfmunger Avatar answered Nov 07 '22 13:11

mrfmunger