替换文档
您可以通过对集合对象使用 ReplaceOne()
同步方法或 ReplaceOneAsync()
异步方法将一个文档替换为另一个文档。
例子
以下代码替换 restaurants
集合中 cuisine
字段值为“Pizza”的第一个文档。替换后,此文档将具有值为“Mongo's Pizza”的 name
字段以及 address
和 borough
字段的新值。
选择 Asynchronous 或 Synchronous 标签页,查看相应的代码。
// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza" var filter = Builders<Restaurant>.Filter .Eq(r => r.Cuisine, "Pizza"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new() { 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"); // Finds the ID of the first restaurant document that matches the filter var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First(); var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant document Restaurant newPizzaRestaurant = new() { Id = oldId, Name = "Mongo's Pizza", Cuisine = "Pizza", Address = new() { 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.
更多信息
要学习;了解有关替换文档的更多信息,请参阅替换操作指南。
如需了解有关使用生成器的更多信息,请参阅生成器操作。