Q:

How can I get a list of databases and collections on a MongoDB server?

I'm writing a GUI client for MongoDB in C. I use the C driver for MongoDB. I want to get a list of databases and their collections, but I can't find any functions in the documentation to do that.
How can I get a list of databases and collections using the C driver?

A:

The other answers here seem half complete, or not even relevant to the C/C++ interface.  After much looking, here's what worked for me:
string serverHost("127.0.0.1:27017");
mongo::DBClientConnection conn;
string errmsg;
if( conn.connect( serverHost, errmsg ) )
{
  BSONObj cmd = mongo::fromjson( "{listDatabases: 1}" );
  BSONObj info;
  if( conn.runCommand( "admin", cmd, info ) )
  {
    BSONElement arrayel = info.getField("databases");
    std::vector<BSONElement> mdArray = arrayel.Array();
    std::vector<BSONElement>::iterator iter;
    for( iter=mdArray.begin(); iter!=mdArray.end(); ++iter )
    {
      BSONElement element = *iter;
      BSONObj obj = element.Obj();

      // HERE IS THE DATABASE NAME
      string dbname = obj.getStringField("name");

      // HERE IS THE LIST OF COLLECTIONS, BUT MAY NEED TO IGNORE ONE
      // TITLED "system.indexes"
      list<string> collNamespaces =
          conn.getCollectionNames(dbname);

      list<string>::iterator iter2 = collNamespaces.begin();
      while( iter2 != collNamespaces.end() )
      {
        // EACH ENTRY HAS THE FULL NAMESPACE ("database:collection").
        // Use this method to strip off the database name
        string collectionName = mongo::nsGetCollection(*iter2);

        ++iter2;
      } // END WHILE iterate through collections
    } // END WHILE iterate through databases
  } // END IF runCommand() returned success
} // END IF database connected

A:

I think you have to use mongo_run_command(mongo *conn, const char * db, bson *command, bson *out) where your command is a BSON command. You should be able to use the commands defined here. Note that some of the commands require that they are issued on the database admin. So in the mongodb shell one could query the list of databases like this:
> use admin
switched to db admin
> db.runCommand({listDatabases: 1})
{
    "databases" : [
        {
            "name" : "geo",
            "sizeOnDisk" : 14975762432,
            "empty" : false
        },
        {
            "name" : "local",
            "sizeOnDisk" : 1,
            "empty" : true
        }
    ],
    "totalSize" : 14975762432,
    "ok" : 1
}

With the result of this operation, you can query each database for the available collections. I haven't tried the above using the C interface, but I believe that you should be able to achieve the same thing by calling mongo_run_command and passing the appropriate parameters.

