谢谢 acm 帮助我解决这个问题,我仍然面临一些问题,因为我是新手,我没有得到正确的语法来遍历代码。
我编写的代码如下:
#include <list>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <cstdint>
#include <iostream>
#include <vector>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/stdx.hpp>
#include <mongocxx/uri.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <mongocxx/options/find.hpp>
#include <bsoncxx/stdx/string_view.hpp>
#include <mongocxx/database.hpp>
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::type;
using namespace bsoncxx;
int main(int, char**)
{
mongocxx::instance inst{};
mongocxx::client conn{mongocxx::uri{}};
auto collection = conn["test"]["restaurants"];
// bsoncxx::stdx::optional<bsoncxx::document::value> maybe_result =collectio n.find_one(document{} << finalize);
mongocxx::cursor cursor = collection.find({});
for (const bsoncxx::document::view& doc :cursor)
{
using std::begin;
using std::end;
auto num_keys = std::distance(begin(doc), end(doc));
std::vector<std::string> doc_keys;
std::transform(begin(doc), end(doc), std::back_inserter(doc_keys), [](document::element ele)
{
return ele.key().to_string();
});
std::cout << "document keys are: " << std::endl;
for (auto key : doc_keys) {
std::cout << key << " " << std::endl;
}
std::cout << std::endl;
}
}
Output:
document keys are:
_id
address
borough
cuisine
grades
name
restaurant_id
document keys are:
_id
address
borough
cuisine
grades
name
restaurant_id
它将输出作为数字返回集合中存在的文档数。我无法遍历主要问题中提到的Find_one()函数。有没有什么方法可以让我只有一次超过价值? [Extract key attributes mongocxx
答案 0 :(得分:1)
您必须使用星号运算符获取可选值,然后从中获取视图。这对我有用:
auto doc = collection.find_one(document{} << finalize);
auto v = (*doc).view();
std::vector<std::string> doc_keys;
for (auto elt : v)
doc_keys.push_back(elt.key().to_string());
std::cout << "document keys are: " << std::endl;
for (auto key : doc_keys) {
std::cout << key << " " << std::endl;
}