2

I am trying to extract only key attributes through mongocxx but using find() and find_one() function .I am not able to pull only key values.

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 =collection.find_one(document{} << finalize);
    if(maybe_result)
    {
       std::cout <<bsoncxx::to_json(*maybe_result)<< "\n";
    }
} 

Above code pull only the one document with keys and their values and I want only keys. Can anyone help me on this?

Shringa Bais
  • 191
  • 2
  • 11
  • MongoDB doesn't work that way. It hands you back the complete document, perhaps projected to certain subtrees, but always including key/value pairs. If you want to do something with the keys, then you should walk the returned document client side (your maybe_result object) and act on the keys that are there. – acm Oct 11 '17 at 13:29
  • But on Mongodb I can able to pull on key attributes: > var coll =db.restaurants.findOne(); > for(var key in coll){print(key);} Outtput- _id address borough cuisine grades name restaurant_id I am trying to pull data something like this through Mongocxx – Shringa Bais Oct 11 '17 at 15:59
  • That code does exactly what I am suggesting. It runs a query on the server via the findOne that returns the whole document, then iterates through that document on the client side extracting the keys. Just do the same thing. Write a for loop that walks the document inside maybe_result and prints the key for each top level item that you find. – acm Oct 11 '17 at 18:04

0 Answers0