Search code examples
attributesmongo-cxx-driver

Extract key attributes mongocxx looping over whole document


Thank you acm for helping me on this, I am still facing few issues as I am new to this I am not getting proper syntax to traverse through the code.

I have written code as follows:

    #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 

It returns output as number the number of documents present in the collection. I am not able to traverse through using Find_one() function as mentioned in main question. Is there any way in which i can get above value as once only? [Extract key attributes mongocxx


Solution

  • You have to get the value of the optional with the star operator then get the view from that. This works for me:

      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;
      }