Update field inside the list using MongoDB C# driver

血红的双手。 提交于 2019-12-24 05:44:30

问题


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}
    ],
}

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


回答1:


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

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



来源:https://stackoverflow.com/questions/54511704/update-field-inside-the-list-using-mongodb-c-sharp-driver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!