How do you update multiple field using Update.Set in MongoDB using official c# driver?

妖精的绣舞 提交于 2019-11-28 07:09:55

It's very simple ;), just add another set or some else operation to the your update:

 var update = Update.Set("Email", "jdoe@gmail.com")
                    .Set("Phone", "4455512");

You can also use the generic and type-safe Update<TDocument>:

var update = Update<Person>.
    Set(p => p.Email, "jdoe@gmail.com").
    Set(p => p.Phone, "4455512");
var _personobj = _person
{
    Id = 10, // Object ID
    Email="jdoe@gmail.com",
    Phone=123456,

};
var replacement = Update<_person>.Replace(_personobj);
collection.Update(myquery, replacement);

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.

if you want to one more update document's field then pick multi flag.

for example mongodb 2.0 or 3.0v:

yourCollection.Update(_filter
                      , _update
                      , new MongoUpdateOptions() { Flags = UpdateFlags.Multi })  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!