使用 monogodb 的C API 來遍歷 bson 的數組對象 數組
使用 bson_printf 打印下數組對象 相似於這樣 app
ips : 4
0 : 3
ip : 2 127.0.0.1:2235
1 : 3
ip : 2 127.0.0.1:9666 socket
一共有3層 第一層是 object 的名字 遍歷的時候使用 bson_find 使用名字查找到 object 後 使用 bson_iterator_subobject 進入這個object 也就是進入 第二層 觀察 第二次 能夠發現 這個 object 的名字是字符的 0 1 2 3 ,,,也就是數組的索引 因此之後 循環構造這樣的字符串 查找每一項 找到一項 就使用 bson_iterator_subobject 進入最後一層 也就是實際的數據了。。。 url
具體 能夠參考下面的代碼 spa
07 |
//Parameters (connection, IP, port); |
08 |
int status = mongo_client(conn, "127.0.0.1", 27017); |
09 |
if(status != MONGO_OK){ |
11 |
case MONGO_CONN_NO_SOCKET: printf("Socket not found\n"); return 1; |
12 |
case MONGO_CONN_FAIL: printf("Connection Failed\n"); return 1; |
13 |
case MONGO_CONN_NOT_MASTER: printf("Not master\n"); return 1; |
18 |
bson_append_string(query,"md5","97296BE70AC48609704936C5BDAF0312"); |
23 |
bson_append_bool(fields,"md5",1); |
24 |
bson_append_bool(fields,"ips",1); |
25 |
bson_append_bool(fields,"urls",1); |
28 |
cursor = mongo_find(conn,"test.virus", query, fields, 9999, 0, 0); |
33 |
while(mongo_cursor_next(cursor) == MONGO_OK) |
35 |
bson_print(mongo_cursor_bson( cursor )); |
37 |
if (bson_find(&it, &cursor->current, "ips")) |
44 |
bson_iterator_subobject( &it, &sub ); |
46 |
while(bson_find(&sub_it,&sub,key)) |
51 |
bson_iterator_subobject( &sub_it, &arr); |
52 |
bson_iterator_init(&bi,&arr); |
53 |
while( (t = bson_iterator_next(&bi))) |
55 |
printf("bson type : %d \n",t); |
65 |
printf("%s \n",bson_iterator_string(&bi)); |
70 |
printf("%s \n",bson_iterator_key(&bi)); |
77 |
mongo_cursor_destroy(cursor); |