对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

更新文档

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() 方法

提示

You can pass an instance of UpdateOptions to the UpdateOne() method in order to customize its behavior.

以下示例使用Buildersrestaurants集合中名为“Bagels N Buns”的第一个文档的name更新为“2 Bagels 2 Buns”。

选择 AsynchronousSynchronous 标签页,查看相应的代码。

// 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 指南。

如需了解有关使用生成器的更多信息,请参阅生成器操作