diff --git a/client/dbclient.cpp b/client/dbclient.cpp index 8e7d4b40c36..0c6b06563ba 100644 --- a/client/dbclient.cpp +++ b/client/dbclient.cpp @@ -288,6 +288,35 @@ namespace mongo { return eval(dbname, jscode, info, retValue); } + list DBClientWithCommands::getDatabaseNames(){ + BSONObj info; + uassert( "listdatabases failed" , runCommand( "admin" , BSON( "listDatabases" << 1 ) , info ) ); + uassert( "listDatabases.databases not array" , info["databases"].type() == Array ); + + list names; + + BSONObjIterator i( info["databases"].embeddedObjectUserCheck() ); + while ( i.more() ){ + names.push_back( i.next().embeddedObjectUserCheck()["name"].valuestr() ); + } + + return names; + } + + list DBClientWithCommands::getCollectionNames( const string& db ){ + list names; + + string ns = db + ".system.namespaces"; + auto_ptr c = query( ns.c_str() , BSONObj() ); + while ( c->more() ){ + string name = c->next()["name"].valuestr(); + if ( name.find( "$" ) != string::npos ) + continue; + names.push_back( name ); + } + return names; + } + void testSort() { DBClientConnection c; string err; diff --git a/client/dbclient.h b/client/dbclient.h index fb4b7fd71d4..6afc9ce95bc 100644 --- a/client/dbclient.h +++ b/client/dbclient.h @@ -482,6 +482,16 @@ namespace mongo { return true; } + /** + get a list of all the current databases + */ + list getDatabaseNames(); + + /** + get a list of all the current collections in db + */ + list getCollectionNames( const string& db ); + virtual string toString() = 0; /** @return the database name portion of an ns string */ diff --git a/client/examples/clientTest.cpp b/client/examples/clientTest.cpp index ce7fc5f0a72..02cd2983479 100644 --- a/client/examples/clientTest.cpp +++ b/client/examples/clientTest.cpp @@ -166,5 +166,17 @@ int main( int argc, const char **argv ) { } + { + list l = conn.getDatabaseNames(); + for ( list::iterator i = l.begin(); i != l.end(); i++ ){ + cout << "db name : " << *i << endl; + } + + l = conn.getCollectionNames( "test" ); + for ( list::iterator i = l.begin(); i != l.end(); i++ ){ + cout << "coll name : " << *i << endl; + } + } + cout << "client test finished!" << endl; }