2013-08-02 42 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