Search code examples
collectionsmongo-cxx-driver

List all the collections of database using mongocxx


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?


Solution

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