插入文档
概述
在此指南中,您可以学习如何使用C驱动程序通过执行插入操作将文档添加到MongoDB集合。
插入操作将一个或多个文档插入到MongoDB集合中。您可以使用以下函数执行插入操作
mongoc_collection_insert_one()
函数用于插入单个文档mongoc_collection_insert_many()
函数用于插入一个或多个文档
示例数据
本指南中的示例使用来自 sample_restaurants
数据库中的 restaurants
集合Atlas 示例数据集。要了解如何创建免费的 MongoDB Atlas 集群并加载示例数据集,请参阅 Atlas 入门指南。
_id 字段
在 MongoDB 集合中,每个文档 必须 包含一个具有唯一字段值的 _id
字段。
MongoDB 允许您以两种方式管理此字段
自行设置每个文档的
_id
字段,确保每个值都是唯一的。让驱动程序自动为每个文档的
_id
字段生成唯一的bson_oid_t
值。
除非您能保证唯一性,否则我们建议让驱动程序自动生成 _id
值。
注意
重复的 _id
值违反了唯一索引约束,这会导致驱动程序返回 mongoc_bulkwriteexception_t
错误。
要了解有关 _id
字段的信息,请参阅 MongoDB 服务器手册中的 唯一索引 指南。
要了解文档结构和规则,请参阅MongoDB服务器手册中的文档指南。
插入一个文档
要将单个文档添加到MongoDB集合中,请调用mongoc_collection_insert_one()
函数,并传递以下参数
要插入文档的集合
要插入的文档
用于自定义操作的选项,或
NULL
指向将包含操作结果的可覆盖存储的指针,或
NULL
错误值的存储位置,或
NULL
以下示例将文档插入到restaurants
集合中
bson_t *document = BCON_NEW ("name", BCON_UTF8 ("Mongo's Burgers")); bson_error_t error; if (!mongoc_collection_insert_one (collection, document, NULL, NULL, &error)) { fprintf (stderr, "Insert one operation failed: %s\n", error.message); } bson_destroy (document);
插入多个文档
要将多个文档添加到MongoDB集合中,请调用mongoc_collection_insert_many()
函数,并传递以下参数
要插入文档的集合
要插入的文档指针数组
要插入的文档数量
用于自定义操作的选项,或
NULL
指向将包含操作结果的可覆盖存储的指针,或
NULL
错误值的存储位置,或
NULL
以下示例将两个文档插入到restaurants
集合中
size_t num_docs = 2; bson_t *docs[num_docs]; docs[0] = BCON_NEW ("name", BCON_UTF8 ("Mongo's Burgers")); docs[1] = BCON_NEW ("name", BCON_UTF8 ("Mongo's Pizza")); bson_error_t error; if (!mongoc_collection_insert_many (collection, (const bson_t **) docs, num_docs, NULL, NULL, &error)) { fprintf (stderr, "Insert many operation failed: %s\n", error.message); } bson_destroy (docs[0]); bson_destroy (docs[1]);
修改插入行为
您可以通过传递一个指定选项值的BSON文档来修改 mongoc_collection_insert_one()
和 mongoc_collection_insert_many()
函数的行为。以下表格描述了您可以在文档中设置的某些选项
选项 | 描述 |
---|---|
bypassDocumentValidation | |
writeConcern | 设置操作的写关注。 默认为命名空间的写关注。 类型: mongoc_write_concern_t |
ordered | 如果设置为 true ,则在插入失败时停止插入文档。如果设置为 false ,则在插入失败时继续插入剩余的文档。您不能将此选项传递给 mongoc_collection_insert_one() 函数。默认为 true 。类型: bool |
comment | 附加到操作的注释。有关更多信息,请参阅 MongoDB 服务器手册中的 插入命令字段 指南。 类型: bson_value_t |
示例
以下代码使用 mongoc_collection_insert_many()
函数将三个新文档插入到集合中。因为 bypassDocumentValidation
字段设置为 true
,因此此插入操作跳过了文档级验证
size_t num_docs = 3; bson_t *docs[num_docs]; docs[0] = BCON_NEW ("name", BCON_UTF8("Mongo's Burgers")); docs[1] = BCON_NEW ("name", BCON_UTF8("Mongo's Pizza")); docs[2] = BCON_NEW ("name", BCON_UTF8("Mongo's Tacos")); bson_t opts; bson_init (&opts); bson_append_bool (&opts, "bypassDocumentValidation", -1, true); bson_error_t error; if (!mongoc_collection_insert_many (collection, (const bson_t **) docs, num_docs, &opts, NULL, &error)) { fprintf (stderr, "Insert many operation failed: %s\n", error.message); } bson_destroy (docs[0]); bson_destroy (docs[1]); bson_destroy (docs[2]); bson_destroy (&opts);
更多信息
API 文档
要了解本指南中讨论的任何函数的更多信息,请参阅以下 API 文档