How do you update multiple field using Update.Set in MongoDB using official c# driver?
It's very simple ;), just add another set or some else operation to the your update:
var update = Update.Set("Email", "[email protected]")
.Set("Phone", "4455512");
You can also use the generic and type-safe Update<TDocument>
:
var update = Update<Person>.
Set(p => p.Email, "[email protected]").
Set(p => p.Phone, "4455512");
For conditional updating you can use something like
var updList = new List<UpdateDefinition<MongoLogEntry>>();
var collection = db.GetCollection<MongoLogEntry>(HistoryLogCollectionName);
var upd = Builders<MongoLogEntry>.Update.Set(r => r.Status, status)
.Set(r => r.DateModified, DateTime.Now);
updList.Add(upd);
if (errorDescription != null)
updList.Add(Builders<MongoLogEntry>.Update.Set(r => r.ErrorDescription, errorDescription));
var finalUpd = Builders<MongoLogEntry>.Update.Combine(updList);
collection.UpdateOne(r => r.CadNum == cadNum, finalUpd, new UpdateOptions { IsUpsert = true });
Or just pop out the record, then modify and replace it.