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

替换文档

在此页面上

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

您可以通过对集合对象使用 ReplaceOne() 同步方法或 ReplaceOneAsync() 异步方法将一个文档替换为另一个文档。

以下代码替换 restaurants 集合中 cuisine 字段值为“Pizza”的第一个文档。替换后,此文档将具有值为“Mongo's Pizza”的 name 字段以及 addressborough 字段的新值。

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

// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza"
var filter = Builders<Restaurant>.Filter
.Eq(r => r.Cuisine, "Pizza");
// Generates a new restaurant document
Restaurant newPizzaRestaurant = new()
{
Name = "Mongo's Pizza",
Cuisine = "Pizza",
Address = new Address()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Asynchronously replaces the existing restaurant document with the new document
return await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);

有关ReplaceOneAsync() 操作的完全可运行示例,请参阅 ReplaceOneAsync 代码示例。

// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza"
var filter = Builders<Restaurant>.Filter
.Eq(r => r.Cuisine, "Pizza");
// Generates a new restaurant document
Restaurant newPizzaRestaurant = new()
{
Name = "Mongo's Pizza",
Cuisine = "Pizza",
Address = new Address()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Replaces the existing restaurant document with the new document
return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);

有关ReplaceOne() 操作的完全可运行示例,请参阅 ReplaceOne 代码示例。

运行上述任一完整示例都会输出以下结果:

First pizza restaurant before replacement: J&V Famous Pizza
Restaurants modified by replacement: 1
First pizza restaurant after replacement: Mongo's Pizza
Resetting sample data...done.

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

后退

更新多个文档