Overview
在本指南中,您可以学习如何使用C驱动程序对MongoDB集合运行替换操作。替换操作的执行方式与更新操作不同。更新操作仅修改目标文档中的指定字段。替换操作会删除目标文档中的所有字段,然后替换为新字段。
要替换文档,请使用 mongoc_collection_replace_one() 函数。
样本数据
The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the MongoDB Get Started guide.
替换操作
您可以使用 mongoc_collection_replace_one() 执行替换操作。 此函数会从匹配搜索条件的第一个文档中删除除 _id字段之外的所有字段。 然后,它将您指定的字段和值插入到文档中。
所需参数
mongoc_collection_replace_one() 函数需要以下参数:
集合:指定要对其执行替换操作的集合。
替换文档:指定要插入到新文档中的字段和值。
选项文档:指定用于自定义操作的选项,或
NULL。结果位置:指定指向将包含操作结果的可覆盖存储的指针,或
NULL。错误位置:指定错误值或
NULL的位置。
例子
以下示例使用 mongoc_collection_replace_one() 函数将 name字段值为 "Pizza Town" 的文档替换为 name字段值为 "Mongo's Pizza" 的文档的字段和值:
bson_t *query = BCON_NEW("name", "Pizza Town"); bson_t *replace = BCON_NEW( "name", "Mongo's Pizza", "cuisine", "Pizza", "address", "{", "street", "123 Pizza St", "zipCode", "10003", "}", "borough", "Manhattan" ); bson_error_t error; if (!mongoc_collection_replace_one(collection, query, replace, NULL, NULL, &error)) { fprintf(stderr, "Replace operation failed: %s\n", error.message); } bson_destroy(query); bson_destroy(replace);
重要
_id 字段的值不可变。 如果替换文档为 _id字段指定了值,则该值必须与现有文档的 _id 值相同。
修改替换操作
您可以通过传递指定选项值的BSON文档来修改 mongoc_collection_replace_one() 函数的行为。 下表描述了您可以在文档中设立的一些选项:
选项 | 说明 |
|---|---|
| |
| |
| |
| 获取或设置用于扫描文档的索引。 有关更多信息,请参阅 MongoDB Server 手册中的提示语句。 |
|
替换选项示例
以下代码使用 mongoc_collection_replace_one() 函数查找 name字段值为 "Food Town" 的第一个文档,然后将该文档替换为 name 值为 "Food World" 的新文档。由于 upsert 选项设立为 true,因此如果查询筛选条件与任何现有文档都不匹配,驱动程序将插入新文档:
bson_t *query = BCON_NEW("name", "Food Town"); bson_t *replace = BCON_NEW( "name", "Food World", "cuisine", "Mixed", "address", "{", "street", "123 Food St", "zipCode", "10003", "}", "borough", "Manhattan" ); bson_error_t error; bson_t opts; bson_init(&opts); bson_append_bool(&opts, "upsert", -1, true); if (!mongoc_collection_replace_one(collection, query, replace, &opts, NULL, &error)) { fprintf(stderr, "Replace operation failed: %s\n", error.message); } bson_destroy(query); bson_destroy(replace); bson_destroy(&opts);
更多信息
要学习;了解有关更新操作的更多信息,请参阅更新文档指南。
要了解创建查询筛选器的更多信息,请参阅指定查询指南。
API 文档
要学习;了解有关 mongoc_collection_replace_one() 函数的详情,请参阅API文档。