替换文档
您可以使用ReplaceOne()
同步方法或集合对象上的 ReplaceOneAsync()
异步方法用另一个文档替换一个文档。
示例
以下代码替换了restaurants
集合中第一个在cuisine
字段中值为"Pizza"的文档。替换后,此文档将有一个name
字段,值为"Mongo's Pizza",以及新的address
和borough
字段值。
选择异步或同步选项卡以查看相应的代码。
// 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.
更多信息
要了解更多关于替换文档的信息,请参阅替换操作指南。
要了解更多关于使用构建器的信息,请参阅使用构建器执行操作。