使用 monogodb 的C API 来遍历 bson 的数组对象
使用 bson_printf 打印下数组对象 类似于这样
ips : 4
0 : 3
ip : 2 127.0.0.1:2235
1 : 3
ip : 2 127.0.0.1:9666
一共有3层 第一层是 object 的名字 遍历的时候使用 bson_find 使用名字查找到 object 后 使用 bson_iterator_subobject 进入这个object 也就是进入 第二层 观察 第二次 可以发现 这个 object 的名字是字符的 0 1 2 3 ,,,也就是数组的索引 所以以后 循环构造这样的字符串 查找每一项 找到一项 就使用 bson_iterator_subobject 进入最后一层 也就是实际的数据了。。。
具体 可以参考下面的代码
int main()
{
mongo conn[1];
mongo_cursor* cursor;
mongo_init_sockets();
//Parameters (connection, IP, port);
int status = mongo_client(conn, "127.0.0.1", 27017);
if(status != MONGO_OK){
switch(conn->err){
case MONGO_CONN_NO_SOCKET: printf("Socket not found\n"); return 1;
case MONGO_CONN_FAIL: printf("Connection Failed\n"); return 1;
case MONGO_CONN_NOT_MASTER: printf("Not master\n"); return 1;
}
}
bson query[1];
bson_init(query);
bson_append_string(query,"md5","97296BE70AC48609704936C5BDAF0312");
bson_finish(query);
bson fields[1];
bson_init(fields);
bson_append_bool(fields,"md5",1);
bson_append_bool(fields,"ips",1);
bson_append_bool(fields,"urls",1);
bson_finish(fields);
cursor = mongo_find(conn,"test.virus", query, fields, 9999, 0, 0);
bson_destroy(query);
bson_destroy(fields);
while(mongo_cursor_next(cursor) == MONGO_OK)
{
bson_print(mongo_cursor_bson( cursor ));
bson_iterator it;
if (bson_find(&it, &cursor->current, "ips"))
{
bson sub;
bson_iterator sub_it;
int idx = 0;
char key[32]={'0',0};
_itoa(idx,key,10);
bson_iterator_subobject( &it, &sub );
bson_print(&sub);
while(bson_find(&sub_it,&sub,key))
{
bson arr;
bson_type t;
bson_iterator bi;
bson_iterator_subobject( &sub_it, &arr);
bson_iterator_init(&bi,&arr);
while( (t = bson_iterator_next(&bi)))
{
printf("bson type : %d \n",t);
switch(t)
{
case BSON_OBJECT:
case BSON_ARRAY:
{
}
break;
case BSON_STRING:
printf("%s \n",bson_iterator_string(&bi));
break;
default:
break;
}
printf("%s \n",bson_iterator_key(&bi));
}
idx++;
_itoa(idx,key,10);
}
}
}
mongo_cursor_destroy(cursor);
mongo_destroy(conn);
return 0;
}