文档菜单
文档首页
/ / /
C#/.NET
/

更新多个文档

在本页

  • 示例
  • 预期结果
  • 更多信息
  • API 文档

您可以使用集合对象的UpdateMany() 方法更新多个文档。

以下代码更新了所有具有“cuisine”字段值为“Pizza”的restaurants集合中的文档。更新后,这些文档的“cuisine”字段值将变为“Pasta and breadsticks”。

选择异步同步选项卡以查看相应的代码。

const string oldValue = "Pizza";
const string newValue = "Pasta and breadsticks";
// Creates a filter for all documents with a "cuisine" value of "Pizza"
var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, oldValue);
// Creates instructions to update the "cuisine" field of documents that
// match the filter
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Cuisine, newValue);
// Updates all documents that have a "cuisine" value of "Pizza"
return await _restaurantsCollection.UpdateManyAsync(filter, update);

有关UpdateManyAsync()操作的完整运行示例,请参阅UpdateManyAsync代码示例.

const string oldValue = "Pizza";
const string newValue = "Pasta and breadsticks";
// Creates a filter for all documents with a "cuisine" value of "Pizza"
var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, oldValue);
// Creates instructions to update the "cuisine" field of documents that
// match the filter
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Cuisine, newValue);
// Updates all documents that have a "cuisine" value of "Pizza"
return _restaurantsCollection.UpdateMany(filter, update);

有关UpdateMany()操作的完整运行示例,请参阅UpdateMany代码示例。

运行上述任何完整示例将打印以下结果

Restaurants with cuisine "Pizza" found: 1163
Restaurants modified by update: 1163
Restaurants with cuisine "Pasta and breadsticks" found after update: 1163
Resetting sample data...done.

要了解有关更新文档的更多信息,请参阅修改文档指南。

要了解有关使用构建器的更多信息,请参阅使用构建器进行操作。

返回

更新文档