2

If you have two independent update objects:

var U1 = Builders<T>.Update.Set(_ => _.A, null);
var U2 = Builders<T>.Update.Set(_ => _.B, null);

How can you chain them so that the result would be:

var U = Builders<T>.Update.Set(_ => _.A, null).Set(_ => _.B, null);

I tried to do this:

var U = U1 & U2;

and, while it works for filters, it doesn't work for updates

2 Answers 2

5

You can add to an existing update definition by appending a new set.

var U1 = Builders<T>.Update.Set(_ => _.A, null);
var U = U1.Set(_ => _.B, null);

I admit that it is a bit funny that the & operator cannot be used for the Update definitions. Also: your own code hints at this as well.

In one of our projects we use this in a loop to construct a combined set of set-operations.

Sign up to request clarification or add additional context in comments.

2 Comments

$addToSet does not add another Set() in a fluent manner, which is what the OP is trying to do. Instead it adds an element to an array.
Thanks for the heads-up. Edited accordingly.
3

You can do something like this if you have multiple conditions or you want to use a foreach loop

var update = Builders<User>.Update.Combine();
if(Name != null)
{
   update = update.Set(Name, newValue);
}

This way you don't have to necessarily initialize the update object with a set statement.

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.