使用MongoDB C#驱动程序更新列表内的字段 [英] Update field inside the list using MongoDB C# driver

查看:81
本文介绍了使用MongoDB C#驱动程序更新列表内的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多个这样的MongoDB文档:

I have multiple MongoDB documents like this:

{
    "_id":"abcde",
    "Students":[
        {"Name":"John","IsNew":true},
        {"Name":"Steve","IsNew":true}
    ],
}

{
    "_id":"fghij",
    "Students":[
        {"Name":"Ron","IsNew":true},
        {"Name":"Mike","IsNew":true}
    ],
}

如何使用C#驱动程序将每个文档的所有学生的IsNew字段更新为false?

How to update the IsNew field to false for all students for every document using C# driver?

推荐答案

您可以将MongoDB C#驱动程序中的UpdateMany方法与

You can use UpdateMany method from MongoDB C# driver with the positional all operator:

var filter = Builders<YourModel>.Filter.Exists(x => x.Students);

FieldDefinition<YourModel, bool> field = "Students.$[].IsNew";
var update = Builders<YourModel>.Update.Set(field, false);

Col.UpdateMany(filter, update);

您可以使用.Exists()作为过滤器,以确保所有正在更新的文档中都存在Students数组

you can use .Exists() as a filter to make sure that Students array is present in all the documents that are being updated

这篇关于使用MongoDB C#驱动程序更新列表内的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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