更新 MongoDb 中对象的所有属性

Update all properties of object in MongoDb

我在我的项目中使用 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 驱动程序更新整个对象?

您可以使用 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);

此代码使用反射来包含给定对象的所有属性
到更新语句,无需手动添加所有属性,因为您看到 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;