加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何编写更新查询以更新mongodb中的多个字段?

发布时间:2020-12-15 04:23:12 所属栏目:百科 来源:网络整理
导读:如何编写此更新查询以更新c#中的mongo记录. db.collection.update({ "S_Id" : 110 },{ "Name" : "Name1","Batch" : "43","Date":"9/2/2011","Status" : 0 }); 我是这样想的 IMongoUpdate update = new UpdateDocument();if (Named != null) { update = Updat
如何编写此更新查询以更新c#中的mongo记录.
db.collection.update({ "S_Id" : 110 },{ "Name" : "Name1","Batch" : "43","Date":"9/2/2011","Status" : 0 });

我是这样想的

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

我做得正确或以何种方式做到这一点,请让我以正确的方式继续下去.

解决方法

在您的示例中,您可能会覆盖每个选项的update值,因此只会向col1.Update()发送单个更新命令.

你会想要使用Update.Combine方法,有点像这样:(未经测试,有点难看……)

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读