You can update a single document using the UpdateOne() method on a MongoCollection object. This method requires a query filter, which specifies which document to update, and an update statement, which specifies the changes the driver should make to the first document matching the query filter.
注意
UpdateOne() 方法仅更新与筛选器匹配的第一个文档。要更新多个文档,请使用 UpdateMany() 方法。
提示
您可以将 UpdateOptions UpdateOne()的实例传递给 方法,以自定义其行为。
例子
以下示例使用Builders将restaurants集合中名为“Bagels N Buns”的第一个文档的name更新为“2 Bagels 2 Buns”。
选择 Asynchronous 或 Synchronous 标签页,查看相应的代码。
// Creates a filter for all documents with a "name" of "Bagels N Buns" var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Name, "Bagels N Buns"); // Creates instructions to update the "name" field of the first document // that matches the filter var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Name, "2 Bagels 2 Buns"); // Updates the first document that has a "name" value of "Bagels N Buns" return await _restaurantsCollection.UpdateOneAsync(filter, update);
有关 UpdateOneAsync() 操作的完全可运行示例,请参阅 UpdateOneAsync 示例。
// Creates a filter for all documents with a "name" of "Bagels N Buns" var filter = Builders<Restaurant>.Filter .Eq(restaurant => restaurant.Name, "Bagels N Buns"); // Creates instructions to update the "name" field of the first document // that matches the filter var update = Builders<Restaurant>.Update .Set(restaurant => restaurant.Name, "2 Bagels 2 Buns"); // 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 对象。
详细信息
要了解有关更新文档的更多信息,请参阅 Update One 指南。
如需了解有关使用生成器的更多信息,请参阅生成器操作。