2013-08-02 78 views
1

我滿足C程序的一個問題connect在MongoDB中檢索文件...我不知道如何解決這個問題,請大家幫幫忙...C不能恢復的MongoDB BSON陣列

記錄結構:

{ "District" : "HK", 
    "Contact": [ {"name":"Person A","telephone":"1111-1111"} , 
       {"name":"Person B", "telephone":"2222-2222} ] 
} 

這裏是我的代碼:

while(mongo_cursor_next(cursor) == MONGO_OK){ 
    bson_iterator iterator[1]; 
    //print district 
    if (bson_find(iterator, mongo_cursor_bson(cursor), "District")) { 
     printf("District: %s\n", bson_iterator_string(iterator)); 

    //print array elements 
    if (bson_find(iterator, mongo_cursor_bson(cursor), "Contact")) { 
     bson_iterator subit[1]; 
     bson_iterator_subiterator(iterator, subit); 

     //get array list element one by one 
     while(bson_iterator_more(subit)){ 
      if(bson_iterator_next(subit)!=BSON_EOO){ 
       bson sub_Object[1]; 
       bson_iterator_subobject_init(subit, sub_Object,1); 
       //bson_print(sub_Object); 

       //comment out the following bson_find could show the expected result 
       if(bson_find(subit, sub_Object, "name")) 
        printf("\tName : %s\n", bson_iterator_string(subit)); 
       if(bson_find(subit, sub_Object, "telephone")) 
        printf("\tTelephone: %s\n", bson_iterator_string(subit)); 

       bson_destroy(sub_Object); 
      } 
     } 
    } 

} 

輸出

區:HK
名稱:某甲
電話:1111至1111年

任何一個知道爲什麼某乙記錄消失?

我有測試,如果while循環切勿使用bson_find第二里面,它可能能夠通過bson_print打印出所有的元素!

是否有關於MongoDB的錯誤?或者我的代碼錯了?

非常感謝!

回答

1

下面subit迭代器創建新的迭代

bson_iterator nInterat[1]; 

bson_iterator subit[1]; 
bson_iterator nInterat[1]; 

,而不是這個

bson_iterator_subobject_init(subit, sub_Object,1) 

變化像

bson_iterator_subobject_init(nInterat, sub_Object,1) 

if(bson_find(nInterat, sub_Object, "name")) 
    printf("\tName : %s\n", bson_iterator_string(nInterat)); 
if(bson_find(nInterat, sub_Object, "telephone")) 
    printf("\tTelephone: %s\n", bson_iterator_string(nInterat)); 

因爲你subit迭代器是當前sub_object指數覆蓋

+0

非常感謝你!!!! – moriya