Docs 菜单
Docs 主页
/ / /
C#/.NET
/

更新多个文档

在此页面上

  • 例子
  • 预期结果
  • 详细信息
  • API 文档

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

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

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

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.

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

后退

更新文档