2017-10-16 25 views
0
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 

Il retourne la sortie en nombre le nombre de documents présents dans la collection. Je ne suis pas capable de traverser en utilisant la fonction Find_one() comme mentionné dans la question principale. Y a-t-il un moyen par lequel je peux obtenir la valeur ci-dessus comme une seule fois? [Extract key attributes mongocxxExtrait attributs clés mongocxx en boucle sur document entier

Répondre

0

Vous devez obtenir la valeur de l'option avec l'opérateur étoile, puis obtenir la vue à partir de cela. Cela fonctionne pour moi:

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