更新 MongoDB 中对象的所有属性

本文关键字:属性 对象 MongoDB 更新 | 更新日期: 2023-09-27 17:56:41

我在我的项目中使用了MongoDB .Net驱动程序。我想更新存储在MongoDB中的对象的所有属性。在文档中,更新如下所示:

var filter = Builders<BsonDocument>.Filter.Eq("i", 10);
var update = Builders<BsonDocument>.Update.Set("i", 110);
await collection.UpdateOneAsync(filter, update);

但我不想对所有属性调用 Set 方法,因为有很多属性,将来可能会有更多属性。

如何使用MongoDB .Net驱动程序更新整个对象?

更新 MongoDB 中对象的所有属性

您可以使用

ReplaceOneAsync而不是UpdateOneAsync来执行此操作。

您需要一个过滤器来匹配现有文档(具有文档 ID 的过滤器是最简单的)和新对象。

Hamster hamster = ...
var replaceOneResult = await collection.ReplaceOneAsync(
    doc => doc.Id == hamster.Id, 
    hamster);
var update = new BsonDocument("$set", new BsonDocument(entityType.GetProperties().Where(p => p.Name != "Id").Select(p => new KeyValuePair<string, object>(p.Name, entityType.GetProperty(p.Name).GetValue(task, null)))));
var options = new UpdateOptions();
collection.UpdateOne<MyTask>(item => item.Name == "cheque", update, options);

此代码使用反射来包含给定对象
的所有属性到更新语句中,无需手动添加所有属性,因为 u 看到 Id 被显式排除在更新语句中以避免异常。

如果要更新整个 BsonDocument,可以从 BsonDocument 隐式转换为 UpdateDefinition。

https://github.com/mongodb/mongo-csharp-driver/blob/master/src/MongoDB.Driver/UpdateDefinition.cs

var doc = new BsonDocument() { .... }
UpdateDefinition<BsonDocument> update = doc;
相关文章: