C# MongoDB 驱动程序 - 如何使用 UpdateDefinitionBuilder? [英] C# MongoDB Driver - How to use UpdateDefinitionBuilder?

查看:109
本文介绍了C# MongoDB 驱动程序 - 如何使用 UpdateDefinitionBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查找了一种使用 mongodb 的 UpdateDefinitionBuilders 的方法,但是 文档 并没有真正显示太多...

I looked up a way to work with mongodb's UpdateDefinitionBuilders but the documentation doesn't really show much...

我需要能够动态构建我的更新查询,所以我想这样做:

I need to be able to dynamically build my update queries, so I thought about doing it like this:

var update = Builders<Product>.Update;

update.Set("add A update");

if ()
    update.Set("add X update");
else
    update.Set("add Y update");

update.Set("add B update");

if ()
    update.Set("add Z update");
else
    update.Set("add P update");

Collection.UpdateOneAsync(filter, update, updateOptions);

但它给出了一个编译错误:

But it gives a compilation error:

无法从 UpdateDefinitionBuilder UpdateDefinition 转换

我查看了但找不到如何使用此 UpdateDefinitionBuilders

I looked, but couldn't find, a solution how to works with this UpdateDefinitionBuilders

谁能提供一个如何使用这个类的代码示例?

Can someone please give a code sample of how to use this class?

推荐答案

如果您需要简单地更新多个属性,您可以在更新构建器上调用 Set ,然后再调用 Set 扩展方法.您可以使用 lambda 表达式或属性名称.

If you need to simply update multiple properties you can call Set on update builder and then make subsequent call to Set extension methods. You can either use lambda expression or property name.

var update = Builders<Product>.Update
    .Set(p => Name, "Name value")
    .Set(p => Description, "Description value");

collection.UpdateOneAsync(filter, update, updateOptions);

如果你想有条件地更新一些属性,你应该创建一个更新的集合,然后组合它们:

If you want conditionally update some properties you should create a collection of the updates and then combine them:

var update = Builders<Product>.Update;
var updates = new List<UpdateDefinition<Product>>();

updates.Add(update.Set("propertyA", "add A update"));

if ()
    updates.Add(update.Set("propertyX", "add X update"));
else
    updates.Add(update.Set("propertyY", "add Y update"));

updates.Add(update.Set(p => p.PropertyB, "add B update"));

if ()
    updates.Add(update.Set(p => p.PropertyZ, "add Z update"));
else
    updates.Add(update.Set(p => p.PropertyP, "add P update"));

Collection.UpdateOneAsync(filter, update.Combine(updates), updateOptions);

这篇关于C# MongoDB 驱动程序 - 如何使用 UpdateDefinitionBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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