替换文档
您可以通过调用 replace_one() 来替换集合中的文档。Collection
方法(针对 实例)。
将以下参数传递给replace_one()
方法:
查询筛选器,指定要匹配的条件
替换文档,其中包含将替换第一个匹配文档的字段和值
replace_one()
方法返回 UpdateResult 类型,包含有关替换操作结果的信息,例如已修改文档的数量。
To learn more about the replace_one()
method, see the Replace a Document section of the Modify Documents guide.
例子
此示例替换sample_restaurants
数据库的restaurants
collection中的文档。Restaurant
该示例使用具有fieldsname
borough
、 和cuisine
字段的 结构体来对collection中的文档进行建模。
以下代码将name
字段的值为"Landmark Coffee Shop"
的文档替换为新文档。MongoDB 会替换与查询筛选器匹配的第一个文档。
选择 Asynchronous或Synchronous标签页,查看每个运行时的相应代码: