private IMongoCollection<Student> _studentCollection```
// get IMongoCollection
...
/// <summary>
/// 批量更新.
/// </summary>
/// <param name="StudentDataList"></param>
/// <returns></returns>
public async Task UpdateManyAsync(IEnumerable<Student> StudentDataList)
{
var models = _studentCollection.Select(studentData=> new ReplaceOneModel<Student>(
new ExpressionFilterDefinition<Student>(studentPo => studentPo.Name == studentData.Name),
studentData)
{
IsUpsert = true,
});
await GPBillScanDataCollection.BulkWriteAsync(models).ConfigureAwait(false);
}
Student是我们操作的对象 StudentPo是MongoDB对象
如果上述批量更新中,抛出objectId
没有赋值的错误,可以使用[BsonIgnoreIfDefault]
特性,如下
/// <summary>
/// 学生对象.
/// </summary>
[MongoDBCollectionName("StudentPo")]
public class StudentPo
{
/// <summary>
/// 主键ID.
/// </summary>
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
/// <summary>
/// 名称.
/// </summary>
public string Name{ get; set; }
}