文档菜单
文档首页
/ / /
C++ 驱动程序
/

从游标中访问数据

在本页

  • 概述
  • 检索所有游标文档
  • 单独检索文档
  • 可尾随游标
  • 更多信息

本指南中,您可以学习如何通过使用C++驱动程序从游标中访问数据。

游标是一种机制,它以可迭代批次的形式返回读取操作的结果。与一次性返回所有文档相比,游标通过在任何给定时间只保留文档的一个子集来减少内存消耗和网络带宽使用。

每当C++驱动程序通过使用find()方法执行读取操作时,它将匹配的文档以mongocxx::cursor实例的形式返回。

本指南中的示例使用来自Atlas示例数据集sample_restaurants数据库中的restaurants集合。要访问C++应用程序中的此集合,请创建一个连接到Atlas集群的mongocxx::client,并将以下值分配给您的dbcollection变量

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

有关如何创建免费的MongoDB Atlas集群并加载数据集的说明,请参阅Atlas入门指南。

要遍历 mongocxx::cursor 实例的内容,请使用 for 循环。

以下示例使用 find() 方法检索所有 name 值为 "Dunkin' Donuts" 的文档。然后它打印出由 find() 方法返回的游标中的每个文档

auto cursor = collection.find(make_document(kvp("name", "Dunkin' Donuts")));
for(auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
{ "_id" : { "$oid" : "..." }, ... "name" : "Dunkin' Donuts", "restaurant_id" : "40379573" }
{ "_id" : { "$oid" : "..." }, ... "name" : "Dunkin' Donuts", "restaurant_id" : "40363098" }
{ "_id" : { "$oid" : "..." }, ... "name" : "Dunkin' Donuts", "restaurant_id" : "40395071" }
...

要从游标中检索单个文档,请对 mongocxx::cursor 实例调用 begin() 方法。此方法返回一个指向游标中第一个文档的 mongocxx::cursor::iterator 实例。

以下示例查找所有具有 name 值为 "Dunkin' Donuts" 的集合中的文档。然后通过调用 begin() 方法打印游标中的第一个文档

auto cursor = collection.find(make_document(kvp("name", "Dunkin' Donuts")));
auto doc = cursor.begin();
std::cout << bsoncxx::to_json(*doc) << std::endl;
{ "_id" : { "$oid" : "..." }, ... "name" : "Dunkin' Donuts", "restaurant_id" : "40379573" }

当在限制集合上进行查询时,您可以使用一个在客户端耗尽游标结果后仍然保持打开状态的可尾游标。要创建可尾游标,实例化一个mongocxx::options::find对象并将其cursor_type字段设置为mongocxx::cursor::type::k_tailable。然后,将您的mongocxx::options::find实例作为参数传递给find()方法。

例如,您可以创建一个名为vegetables的限制集合,用于存储代表蔬菜的文档,如下面的代码所示

auto db = client["db"];
auto collection = db.create_collection("vegetables", make_document(kvp("capped", true), kvp("size", 1024 * 1024)));
std::vector<bsoncxx::document::value> vegetables;
vegetables.push_back(make_document(kvp("name", "cauliflower")));
vegetables.push_back(make_document(kvp("name", "zucchini")));
auto result = collection.insert_many(vegetables);

以下代码使用可尾游标检索vegetables集合中的所有文档。在游标耗尽后,它保持打开状态,直到检索到三个文档

mongocxx::options::find opts{};
opts.cursor_type(mongocxx::cursor::type::k_tailable);
auto cursor = collection.find({}, opts);
int docs_found = 0;
while (docs_found < 3) {
for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
docs_found++;
}
// Sleeps for 100 milliseconds before trying to access more documents
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
{ "_id" : { "$oid" : "..." }, "name" : "cauliflower" }
{ "_id" : { "$oid" : "..." }, "name" : "zucchini" }

如果您向vegetables集合中插入另一个文档,前面的代码将打印新文档并关闭while循环。

有关可尾游标的更多信息,请参阅MongoDB服务器手册中的可尾游标指南

有关读取操作的更多信息,请参阅检索数据指南。

有关本指南中讨论的任何方法或类型的更多信息,请参阅以下API文档

返回

计算文档数