Docs 菜单

Docs 主页C++ 驱动程序

教程

在此页面上

  • 先决条件
  • 编译
  • 建立连接
  • 访问数据库
  • 访问集合
  • 创建文档
  • 插入文档
  • 插入一个文档
  • 插入多个文档
  • 查询集合
  • 在collection中查找单个文档
  • 查找集合中的所有文档
  • 打印collection中的所有文档
  • 指定查询筛选器
  • 更新文档
  • 更新单份文档
  • 更新多个文档
  • 删除文档
  • 删除单个文档
  • 删除与筛选器匹配的所有文档
  • 创建索引

请参阅 tutorial.cpp 中本教程的完整代码。

  • 在本地主机的端口27017上运行的mongod实例。

  • mongocxx 驱动程序。请参阅安装。

  • 源声明顶部的以下文件:

#include <cstdint>
#include <iostream>
#include <vector>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_array;
using bsoncxx::builder::basic::make_document;

mongocxx 驱动程序的安装过程将安装一个与libmongocxx.pc pkg-config 一起使用的 文件。

要编译程序,请运行以下命令:

c++ --std=c++11 <input>.cpp $(pkg-config --cflags --libs libmongocxx)

如果没有可用的 pkg-config,则需要在命令行或 IDE 中手动设置包含和库标志。例如,如果 libmongoc 和 mongocxx 安装在/usr/local中,则上面的编译行将扩展为:

c++ --std=c++11 <input>.cpp
-I/usr/local/include/mongocxx/v_noabi \
-I/usr/local/include/bsoncxx/v_noabi \
-L/usr/local/lib -lmongocxx -lbsoncxx

重要

在建立任何连接之前,您需要创建一个且仅一个 mongocxx::instance 实例 。此实例必须在整个程序中存在。

要连接到正在运行的 MongoDB 实例,请使用 mongocxx::instance 类。

必须使用 mongocxx::uri 指定要连接的主机 实例 ,并将其传递给mongocxx::client 构造函数。有关支持的 URI 选项的详细信息,请参阅用于构建 C# 驱动程序的 libmongoc 版本或 最新 libmongoc 版本的文档。

默认的mongocxx::uri构造函数将连接到在端口27017上的本地主机上运行的服务器:

mongocxx::instance instance{}; // This should be done only once.
mongocxx::client client{mongocxx::uri{}};

这相当于以下内容:

mongocxx::instance instance{}; // This should be done only once.
mongocxx::uri uri("mongodb://localhost:27017");
mongocxx::client client(uri);

拥有 mongocxx::instance 后 连接到 MongoDBdatabase() operator[]部署的实例,请使用 方法或 获取 mongocxx::database 实例。

如果您请求的数据库不存在,MongoDB 会在您首次存储数据时创建该数据库。

以下示例将访问mydb数据库:

auto db = client["mydb"];

拥有 数据库 实例,使用collection() 方法或operator[] 获取 collection 实例。

如果您请求的集合不存在,MongoDB 会在您首次存储数据时创建该集合。

例如,使用上一节中创建的db实例,以下声明访问mydb数据库中名为test的collection:

auto collection = db["test"];

要使用 C++ 驱动程序创建document ,请使用两个可用的构建器接口之一:

  • 流构建器: bsoncxx::builder::stream
    使用流媒体操作符的文档构建器,非常适合字面文档构建。
  • 基本生成器: bsoncxx::builder::basic
    一种更传统的文档生成器,涉及在生成器实例上调用方法。

本指南仅简要描述基本构建器。

例如,考虑以下 JSON document:

{
"name" : "MongoDB",
"type" : "database",
"count" : 1,
"versions": [ "v6.0", "v5.0", "v4.4", "v4.2", "v4.0", "v3.6" ],
"info" : {
"x" : 203,
"y" : 102
}
}

使用基本构建器接口,可以按如下方式构建此文档:

auto doc_value = make_document(
kvp("name", "MongoDB"),
kvp("type", "database"),
kvp("count", 1),
kvp("versions", make_array("v6.0", "v5.0", "v4.4", "v4.2", "v4.0", "v3.6")),
kvp("info", make_document(kvp("x", 203), kvp("y", 102)))
);

bsoncxx::document::value 类型是只读对象,拥有自己的内存。要使用它,必须获取 bsoncxx::文档::view 使用view() 方法:

auto doc_view = doc_value.view();

您可以使用 访问此文档视图中的字段,这将返回operator[] bsoncxx::document::element 实例。例如,以下命令将提取值为字符串的name 字段:

auto element = doc_view["name"];
assert(element.type() == bsoncxx::type::k_string);
auto name = element.get_string().value; // For C++ driver version < 3.7.0, use get_utf8()
assert(0 == name.compare("MongoDB"));

如果 name 字段中的值不是字符串,并且没有包含上例中所示的类型保护,则此代码将抛出 bsoncxx::Exception 的实例。

要将单个文档插入到集合中,请使用 mongocxx::collection 实例的 insert_one()方法插入{ "i": 0 }

auto insert_one_result = collection.insert_one(make_document(kvp("i", 0)));

insert_one_result 是可选的 mongocxx::result::insert_one 。在此示例中,应设置insert_one_result 。写入操作的默认行为是等待服务器的回复。这可以通过设置未确认的 mongocxx::write_concern 来覆盖。

assert(insert_one_result); // Acknowledged writes return results.

如果未在文档中指定顶级_id字段,MongoDB 会自动将_id字段添加到插入的文档中。

您可以使用返回的inserted_id() mongocxx::result::insert_one 的 方法获取此值 实例。

auto doc_id = insert_one_result->inserted_id();
assert(doc_id.type() == bsoncxx::type::k_oid);

要将多个文档插入到集合中,请使用 mongocxx::collection 实例的insert_many() 方法,该方法获取要插入的文档列表。

以下示例将插入文档{ "i": 1 }{ "i": 2 } 。创建文档并添加到文档列表中:

std::vector<bsoncxx::document::value> documents;
documents.push_back(make_document(kvp("i", 1)));
documents.push_back(make_document(kvp("i", 2)));

要将这些文档插入到collection中,请将文档列表传递给insert_many()方法。

auto insert_many_result = collection.insert_many(documents);
assert(insert_many_result); // Acknowledged writes return results.

如果没有在每个文档中指定顶级_id字段,MongoDB 会自动向插入的文档添加一个_id字段。

您可以使用返回的inserted_ids() mongocxx::result::insert_many 的 方法获取此值 实例。

auto doc0_id = insert_many_result->inserted_ids().at(0);
auto doc1_id = insert_many_result->inserted_ids().at(1);
assert(doc0_id.type() == bsoncxx::type::k_oid);
assert(doc1_id.type() == bsoncxx::type::k_oid);

要查询集合,请使用集合的find()find_one()方法。

find() 将返回 游标 的实例 ,而find_one() 将返回std::optional< bsoncxx::document::value > 的实例。有关详细信息,请参阅 文档。

您可以使用空文档调用任一方法来查询collection中的所有文档,也可以传递筛选器来查询与筛选条件匹配的文档。

要返回collection中的单个文档,请使用不带任何参数的find_one()方法。

auto find_one_result = collection.find_one({});
if (find_one_result) {
// Do something with *find_one_result
}
assert(find_one_result);
auto cursor_all = collection.find({});
for (auto doc : cursor_all) {
// Do something with doc
assert(doc["_id"].type() == bsoncxx::type::k_oid);
}

bsoncxx::to_json 函数将 BSON 文档转换为 JSON 字符串。

auto cursor_all = collection.find({});
std::cout << "collection " << collection.name()
<< " contains these documents:" << std::endl;
for (auto doc : cursor_all) {
std::cout << bsoncxx::to_json(doc, bsoncxx::ExtendedJsonMode::k_relaxed) << std::endl;
}
std::cout << std::endl;

上述示例的打印输出类似于以下内容:

collection test contains these documents:
{ "_id" : { "$oid" : "6409edb48c37f371c70f03a1" }, "i" : 0 }
{ "_id" : { "$oid" : "6409edb48c37f371c70f03a2" }, "i" : 1 }
{ "_id" : { "$oid" : "6409edb48c37f371c70f03a3" }, "i" : 2 }

_id元素已由 MongoDB 自动添加到您的文档中,您的值将与显示的不同。 MongoDB 保留以下划线 ( _ ) 和美元符号 ( $ ) 开头的字段名称供内部使用。

要查找字段i的值为0的第一个文档,请传递文档{"i": 0}以指定相等条件:

auto find_one_filtered_result = collection.find_one(make_document(kvp("i", 0)));
if (find_one_filtered_result) {
// Do something with *find_one_filtered_result
}

以下示例获取所有包含0 < "i" <= 2的文档:

auto cursor_filtered =
collection.find(make_document(kvp("i", make_document(kvp("$gt", 0), kvp("$lte", 2)))));
for (auto doc : cursor_filtered) {
// Do something with doc
assert(doc["_id"].type() == bsoncxx::type::k_oid);
}

要更新集合中的文档,可以使用集合的update_one()update_many()方法。

更新方法返回std::optional< mongocxx::result::update > 的实例,其中提供有关操作的信息,包括更新修改的文档数。有关更多信息,请参阅 mongocxx::result::update。

要最多更新一个文档,请使用update_one()方法。

以下示例更新与筛选器{ "i": 0 }匹配的第一个文档,并将foo的值设置为bar

auto update_one_result =
collection.update_one(make_document(kvp("i", 0)),
make_document(kvp("$set", make_document(kvp("foo", "bar")))));
assert(update_one_result); // Acknowledged writes return results.
assert(update_one_result->modified_count() == 1);

要更新与筛选器匹配的所有文档,请使用update_many()方法。

以下示例将foo的值设置为buzz ,其中i大于0

auto update_many_result =
collection.update_many(make_document(kvp("i", make_document(kvp("$gt", 0)))),
make_document(kvp("$set", make_document(kvp("foo", "buzz")))));
assert(update_many_result); // Acknowledged writes return results.
assert(update_many_result->modified_count() == 2);

要从集合中删除文档,可以使用集合的delete_one()delete_many()方法。

删除方法返回实例的std::optional< mongocxx::result::delete > ,其中包含已删除的文档数。有关更多信息,请参阅 mongocxx::result::delete。

要最多删除与过滤器匹配的文档,请使用delete_one()方法。

例如,要删除与过滤器{ "i": 0 }匹配的文档:

auto delete_one_result = collection.delete_one(make_document(kvp("i", 0)));
assert(delete_one_result); // Acknowledged writes return results.
assert(delete_one_result->deleted_count() == 1);

要删除与筛选器匹配的所有文档,请使用集合的delete_many()方法。

以下示例删除i大于0的所有文档:

auto delete_many_result =
collection.delete_many(make_document(kvp("i", make_document(kvp("$gt", 0)))));
assert(delete_many_result); // Acknowledged writes return results.
assert(delete_many_result->deleted_count() == 2);

要在一个字段或一组字段上创建 索引create_index() ,请将索引规范文档传递给 mongocxx::collection 的 方法 实例。索引键规范文档包含要索引的字段以及每个字段的索引类型:

{ "index1": "<type>", "index2": "<type>" }
  • 对于升序索引类型,请为 指定1 <type>

  • 对于降序索引类型,请为 指定 -1 <type>

以下示例在i字段上创建一个升序索引:

auto index_specification = make_document(kvp("i", 1));
collection.create_index(std::move(index_specification));
←  客户端字段级加密 (Client-Side Field Level Encryption)线程和分叉安全 →