开心123 发表于 2015-11-10 14:02:55

mongodb中用C语言遍历数据库中所有集合名

        最近项目中要用到c遍历mongodb数据库中所有集合名,从网上找了半天也没找到相关资料,
  官方c驱动也没提供相应的capi,最后参考matlab驱动获取集合名的函数,改造了一个c获取数据
  库所有集合名的函数,下面直接上完整代码。
  
  一、源码
  #include <stdio.h>
#include <mongo.h>
  
  /********************************************************
**函数:mongo_iterator_collection_name
**
**功能:遍历出mongodb数据库中的所有集合名
**
**参数:conn -- 连接数据库句柄
**      db   -- 要遍历的数据库名
**
**返回值:无
**/
  static void mongo_iterator_collection_name( mongo *conn, const char *db)
{
         mongo_cursor cursor;
         char tmp;

         //要遍历数据库集合的命名空间为:数据库名.system.namespaces
      sprintf(tmp, &quot;%s.system.namespaces&quot;, db);
      mongo_cursor_init( cursor, conn, tmp );
      while( mongo_cursor_next( cursor ) == MONGO_OK )
      {
               bson_iterator iterator;
               if ( bson_find( iterator, mongo_cursor_bson( cursor ), &quot;name&quot; ))
               {
                     const char *name = bson_iterator_string( iterator );
                     //过滤其他集合名
                     if(strstr(name, &quot;system&quot;) != NULL || strstr(name, &quot;$&quot;) != NULL)
                     {
                              continue;
                     }

                      //输出需要的集合名,结果以:&quot;数据库名.集合名&quot;的形式输出
                     printf( &quot;%s\n&quot;,name);
                }
      }
  mongo_cursor_destroy( cursor );
}
  
  //main 函数
  int main()
{
       mongo conn;

       int status = mongo_client(&conn, &quot;127.0.0.1&quot;, 27017 );
      if( status != MONGO_OK )
      {
            switch ( conn.err )
            {
               case MONGO_CONN_NO_SOCKET:
               {
                        printf( &quot;no socket\n&quot; );
                        return 1;
                  }
               case MONGO_CONN_FAIL:
               {
                     printf( &quot;connection failed\n&quot; );
                     return 1;
               }
               case MONGO_CONN_NOT_MASTER:
               {
                     printf( &quot;not master\n&quot; );
                     return 1;
                  }
            }
       }

      //开始遍历
       mongo_iterator_collection_name(&conn, &quot;test&quot;);

       mongo_destroy(&conn );
  return 0;
}
  
  二、makefile内容
  # Makefile for mongodb test.
CC   := gcc
  # Include paths(mongo.h)
INCS := -I/usr/local/include/
  # Lib paths(libmongoc.so)
LIB := -L/usr/local/lib/ -lmongoc
  # Targets of the build
OUTPUT := Main
  # Source files
  SRCSOBJS := test.c
  # common rules
  ${OUTPUT} : ${SRCSOBJS}
${CC} ${SRCSOBJS} ${INCS} ${LIB} -o ${OUTPUT}
  clean:
-rm -f ${OUTPUT}
  
  三、进入mongodb的客户端shell,可以查看test数据库的集合信息如下:

  
  四、运行测试代码的makefile,然后运行./Main,可以有如下结果

  
  结果无误,遍历函数可行。
  
         版权声明:本文为博主原创文章,未经博主允许不得转载。
页: [1]
查看完整版本: mongodb中用C语言遍历数据库中所有集合名