0

I have been trying to pull list of all the collections present in database and trying to use :

cursor list_collections(bsoncxx::document::view filter = {});

but not able to iterate over the collections.

Can anyone help me on this?

Renis1235
  • 4,116
  • 3
  • 15
  • 27
Shringa Bais
  • 191
  • 2
  • 11

1 Answers1

4

Got the answer:

int main(int, char**)
{
    mongocxx::instance inst{};
    mongocxx::client conn{mongocxx::uri{}};
   // auto collection = conn["test"]["restaurants"];
    mongocxx::database db = conn["test"];
    auto cursor1 = db.list_collections();
    for (const bsoncxx::document::view& doc :cursor1)
    {
        bsoncxx::document::element ele = doc["name"];
        std::string name = ele.get_utf8().value.to_string();
        std::cout <<name<< std::endl;

    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Shringa Bais
  • 191
  • 2
  • 11
  • 2
    You can also use `db.list_collection_names()` which returns an `std::vector`, so: `for (const auto& name : db.list_collection_names()) std::cout << name << '\n';` – Octo Poulos Mar 24 '22 at 13:52