对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

替换文档

可以通过对集合对象使用 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 filtervar oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();var oldId = oldPizzaRestaurant.Id; // Generates a new restaurant documentRestaurant newPizzaRestaurant = new(){ Id = oldId, 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 documentreturn await _restaurantsCollection.ReplaceOneAsync(filter, newPizzaRestaurant);

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

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

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

要学习;了解有关替换文档的更多信息,请参阅替换文档指南。

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