bson 数组对象的遍历

   使用 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;
}

转载于:https://my.oschina.net/sincoder/blog/112933

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值