1

我在 C 程序连接到 mongodb 以检索文档时遇到问题...我不知道如何解决,请帮助...

记录结构:

{ "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);
            }
        }
   }

}

输出

地区:香港
姓名:A 人
电话:1111-1111

有谁知道为什么B人的记录消失了??

我已经测试了是否在第二个 while 循环中不使用 bson_find,它可以通过 bson_print 打印出所有元素!

mongodb有bug吗??还是我的代码错了?

非常感谢!!!

4

1 回答 1

1

创建新的迭代器

 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 索引覆盖

于 2013-09-24T05:43:51.077 回答