2013-05-11 79 views
1

我想運行一個查詢,只從MongoDB獲取不同的值。我運行了查詢並返回了正確的值,但我不確定如何使用C API迭代生成的BSON數組。查詢不同的值,並遍歷結果MongoDB C API

這裏是代碼:

bson query; 
bson out; 

bson_init(&query); 
bson_append_string(&query, "distinct", "myCollection"); 
bson_append_string(&query, "key", "someKey"); 
bson_finish(&query); 

if (mongo_run_command(conn, "myDB", &query, &out) != MONGO_OK) { 
    printf("mongo_run_command failed!\n"); 
    return 1; 
} 
else { 
while(bson_iterator_next(out)){ 
    bson iterator; 
    if (bson_find(iterator, &out, "someKey")) { 
     printf("%s\n", bson_iterator_string(iterator)); 
    } 
} 
bson_print(&out); 

bson_print(&out)並打印出正確的數組,但我怎麼能循環數組了嗎?

C API的文檔在地面上非常薄,甚至不包含mongo_run_command

任何幫助表示讚賞

回答

0

我解決了它。對於那些正在尋找這裏的解決方案是對我工作:

bson outSub[1]; 
bson_iterator iterator[1]; 
bson_iterator iterator2[1]; 
bson_type type; 
const char *value; 

// advance to the values array 
bson_find(iterator, out, "values"); 
bson_iterator_subobject_init(iterator, outSub, 0); 

bson_iterator_init(iterator2, outSub); 
while (bson_iterator_more(iterator2)) { 
    type = bson_iterator_next(iterator2); 
    value = bson_iterator_string(iterator2); 
    if (strlen(value) > 0) { 
     printf("Value: %s\n", value); 
    } 
} 
bson_destroy(outSub); 

它還清檢查出附帶C API的樣本:)