更新文档
您可以使用以下方法更新单个文档:UpdateOne() 方法在MongoCollection
对象上。此方法需要一个 查询过滤器,用于指定要更新的文档,以及一个 更新 语句,用于指定驱动程序应该对与查询过滤器匹配的第一个文档进行的更改。
注意
UpdateOne()
方法仅更新匹配过滤器的一个文档。要更新多个文档,请使用UpdateMany() 方法.
技巧
您可以将 UpdateOptions 的实例传递给 UpdateOne()
方法,以自定义其行为。
示例
以下示例使用 Builders
更新名为 "Bagels N Buns" 的第一个文档在 restaurants
集合中的名称为 "2 Bagels 2 Buns"。
选择异步 或 同步 选项卡以查看相应的代码。
const string oldValue = "Bagels N Buns"; const string newValue = "2 Bagels 2 Buns"; // Creates a filter for all documents with a "name" of "Bagels N Buns" var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Name, oldValue); // Creates instructions to update the "name" field of the first document // that matches the filter var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Name, newValue); // Updates the first document that has a "name" value of "Bagels N Buns" return await _restaurantsCollection.UpdateOneAsync(filter, update);
有关 UpdateOneAsync()
操作的完整可运行示例,请参阅UpdateOneAsync 示例。
const string oldValue = "Bagels N Buns"; const string newValue = "2 Bagels 2 Buns"; // Creates a filter for all documents with a "name" of "Bagels N Buns" var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Name, oldValue); // Creates instructions to update the "name" field of the first document // that matches the filter var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Name, newValue); // Updates the first document that has a "name" value of "Bagels N Buns" return _restaurantsCollection.UpdateOne(filter, update);
有关 UpdateOneAsync()
操作的完整可运行示例,请参阅UpdateOne 示例。
预期结果
在运行上述任意一个完整示例之后,每次调用UpdateOne()
都会将以下内容写入控制台
Updated documents: 1
技巧
UpdateOne()
返回一个UpdateResult对象。
更多信息
要了解更多关于更新文档的信息,请参阅修改文档指南。
要了解更多关于使用构建器的信息,请参阅使用构建器进行操作。