最近項目中要用到c遍歷mongodb數據庫中所有集合名,從網上找了半天也沒找到相關資料,
官方c驅動也沒提供相應的c api,最後參考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[1];
char tmp[128];
//要遍歷數據庫集合的命名空間爲:數據庫名.system.namespaces
sprintf(tmp, "%s.system.namespaces", db);
mongo_cursor_init( cursor, conn, tmp );
while( mongo_cursor_next( cursor ) == MONGO_OK )
{
bson_iterator iterator[1];
if ( bson_find( iterator, mongo_cursor_bson( cursor ), "name" ))
{
const char *name = bson_iterator_string( iterator );
//過濾其他集合名
if(strstr(name, "system") != NULL || strstr(name, "$") != NULL)
{
continue;
}
//輸出需要的集合名,結果以:"數據庫名.集合名"的形式輸出
printf( "%s\n", name);
}
}
mongo_cursor_destroy( cursor );
}
//main 函數
int main()
{
mongo conn;
int status = mongo_client(&conn, "127.0.0.1", 27017 );
if( status != MONGO_OK )
{
switch ( conn.err )
{
case MONGO_CONN_NO_SOCKET:
{
printf( "no socket\n" );
return 1;
}
case MONGO_CONN_FAIL:
{
printf( "connection failed\n" );
return 1;
}
case MONGO_CONN_NOT_MASTER:
{
printf( "not master\n" );
return 1;
}
}
}
//開始遍歷
mongo_iterator_collection_name(&conn, "test");
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,可以有如下結果
結果無誤,遍歷函數可行。