怎样写更新查询更新MongoDB的多个字段? [英] How to write update query to update multiple fields in mongodb?

查看:2933
本文介绍了怎样写更新查询更新MongoDB的多个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编写用于更新在C#中蒙戈记录此更新查询。

How to write this update query for updating a mongo record in c#.

db.collection.update({ "S_Id" : 110 },{ "Name" : "Name1","Batch" : "43","Date":"9/2/2011",  "Status" : 0 }); 



我'尝试这样

I'am trying like this

IMongoUpdate update = new UpdateDocument();
if (Named != null) { update = Update.Set("Name", "Name1"); }
if (Date != null) { update = Update.Set("Date", "18/02/2013"); }
if (Batch != null) { update = Update.Set("Batch",43); }
coll.Update(query, update);



是我'做正确的或我必须做什么样的方式,请让我正确的的方式来进行。

was I'am doing correct or in what way i have to do it, please make me the correct way to proceed.

推荐答案

在你的榜样,你可能覆盖更新值每个选项,所以将只发送单个update命令 col1.Update()

In your example, you are potentially overwriting the value of update for each option, so will only be sending a single update command to col1.Update().

你将要使用 Update.Combine 方法,隐约的东西是这样的:(未经测试,并且有点难看......)

you will want to use the Update.Combine method, something vaguely like this: (untested, and a bit ugly...)

    var updateValues = new List<UpdateBuilder>();
    if (Named != null) { updateValues.Add(Update.Set("Name", "Name1")); }
    if (Date != null) { updateValues.Add(Update.Set("Date", "18/02/2013")); }
    if (Batch != null) { updateValues.Add(Update.Set("Batch", 43)); }
    IMongoUpdate update = Update.Combine(updateValues);
    coll.Update(query, update);

这篇关于怎样写更新查询更新MongoDB的多个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆