Docs 菜单
Docs 主页
/ / /
C++ 驱动程序
/

插入文档

在此页面上

  • Overview
  • 样本数据
  • _id 字段
  • 插入一个文档
  • 插入多个文档
  • 修改插入行为
  • 例子
  • 更多信息
  • API 文档

在本指南中,您可以学习;了解如何使用C++驾驶员通过执行插入操作将文档添加到MongoDB集合。

插入操作将一个或多个文档插入MongoDB集合。 您可以使用 insert_one()方法插入单个文档或使用insert_many()方法插入一个或多个文档来执行插入操作。

本指南中的示例使用 Atlas示例数据集中sample_restaurants.restaurants集合。 要从C++应用程序访问权限此集合,请实例化一个连接到Atlas 集群的client ,并将以下值分配给dbcollection变量:

auto db = client["sample_restaurants"];
auto collection = db["restaurants"];

要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅Atlas入门指南。

在 MongoDB 集合中,每个文档必须包含具有唯一字段值的 _id 字段。

MongoDB 允许您通过两种方式管理该字段:

  • 您可以自行为每个文档设置此字段,确保每个 _id 字段的值都是唯一的。

  • 您可以让驱动程序为每个文档 _id 自动生成唯一的 ObjectId 值。

除非您可以保证唯一性,否则我们建议让驱动程序自动生成_id值。

注意

重复的_id值违反了唯一索引约束,导致驾驶员返回mongocxx::bulk_write_exception错误。

要了解有关_id字段的更多信息,请参阅 MongoDB Server 手册中的唯一索引指南。

要了解有关文档结构和规则的更多信息,请参阅 MongoDB Server 手册中的文档指南。

要将单个文档添加到 MongoDB 集合,请调用insert_one()方法并传递要添加的文档。

以下示例将文档插入restaurants集合:

auto result = collection.insert_one(make_document(kvp("name", "Mongo's Burgers")));

要将多个文档添加到MongoDB集合,请调用insert_many()方法并传递用于存储要添加的文档的向量。

以下示例将两个文档插入restaurants集合:

std::vector<bsoncxx::document::value> restaurants;
restaurants.push_back(make_document(kvp("name", "Mongo's Burgers")));
restaurants.push_back(make_document(kvp("name", "Mongo's Pizza")));
auto result = collection.insert_many(restaurants);

您可以通过将mongocxx::options::insert类的实例作为可选参数传递来修改insert_one()insert_many()方法的行为。 下表描述了您可以在mongocxx::options::insert实例中设立的字段:

字段
说明
bypass_document_validation
If set to true, allows the write to opt out of document-level validation.
Defaults to false.
Type: bool
write_concern
Sets the write concern for the operation.
Defaults to the write concern of the namespace.
Type: mongocxx::write_concern
ordered
If set to true, the operation stops inserting documents when one insert fails. If false, the operation continues to insert the remaining documents when one insert fails.
Defaults to true.
Type: bool
comment
A comment to attach to the operation. For more information, see the insert command fields guide in the MongoDB Server manual.
Type: bsoncxx::types::bson_value::view_or_value

以下代码使用insert_many()方法将三个新文档插入到集合中。 由于bypass_document_validation字段在mongocxx::options::insert实例中设立为true ,因此此插入操作会绕过文档级验证:

std::vector<bsoncxx::document::value> docs;
docs.push_back(make_document(kvp("name", "Mongo's Burgers")));
docs.push_back(make_document(kvp("name", "Mongo's Pizza")));
docs.push_back(make_document(kvp("name", "Mongo's Tacos")));
mongocxx::options::insert opts;
opts.bypass_document_validation(true);
auto result = collection.insert_many(docs, opts);

有关使用C++驾驶员插入文档的可运行代码示例,请参阅将数据写入MongoDB。

要进一步了解本指南所讨论的任何方法或类型,请参阅以下 API 文档:

后退

将数据写入 MongoDB