Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs 菜单
Docs 主页
/ / /
C++ 驱动程序

Tutorial

请参阅 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:: 实例实例。此实例必须在整个程序中存在。

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

您必须使用包含MongoDB URI mongocxx::client的 mongocxx::uri实例指定要连接的托管,并将其传递给 构造函数。有关支持的 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:: 实例实例连接到MongoDB 部署后,使用database() 方法或operator[] 获取 mongocxx:: 数据库实例。

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

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

auto db = client["mydb"];

获得 mongocxx::数据库实例后,使用 collection()方法或 获取operator[] mongocxx::集合实例。

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

例如,使用上一节中创建的db实例,以下语句访问mydb数据库中名为test的集合:

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:: 文档::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::集合实例的 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::集合实例的 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)));

要将这些文档插入到集合中,请将文档列表传递给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() 将返回 mongocxx:: 游标的实例,而find_one() 将返回std::optional< bsoncxx::document::value > 的实例。有关更多信息,请参阅 bsoncxx:: 文档::value。

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

要返回集合中的单个文档,请使用不带任何参数的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_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_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::集合实例的 方法。索引键规范文档包含要索引的字段以及每个字段的索引类型:

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

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

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

auto index_specification = make_document(kvp("i", 1));
collection.create_index(std::move(index_specification));

后退

客户端加密

在此页面上