c - 如何获取 MongoDB 服务器上的数据库和集合列表?

标签 c mongodb

我正在用 C 为 MongoDB 编写一个 GUI 客户端。我使用 C driver for MongoDB .我想获取数据库及其集合的列表,但在 documentation 中找不到任何函数这样做。

如何使用 C 驱动程序获取数据库和集合的列表?

最佳答案

这里的其他答案似乎只完成了一半,或者甚至与 C/C++ 接口(interface)无关。看了很多之后,这是对我有用的:

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

关于c - 如何获取 MongoDB 服务器上的数据库和集合列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8286994/

相关文章:

c - 使用 scanf 输出 x 的标准逻辑函数?

c - 使用链接列表读取文本文件

c - 如何在 Windows 中使用 crypt(3)?

MongoDB 搜索 "null"是否比搜索 "does not exist"更快?

mongodb - "db.createUser is not a function"和 "password can' 为空”

mongodb - Mongodb无分组平均聚合查询

c - 从不兼容的指针类型解析 CreateFileA 的参数 1(尝试从文件内容创建哈希)

c - C 中的 hadoop hdfs 客户端

mongodb - 副本集和MongoDB,选项{w : 1} make the system AP in terms of CAP?

mongodb - mongoengine 查询嵌入文档列表