1

I meet a problem on C program connect to mongodb to retrieve document...I dont know how to solve it, please help...

The record structure :

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

Here is my code:

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

}

Output

District: HK
Name: Person A
Telephone: 1111-1111

Any one know why Person B record disappear??

I have test if DO NOT use bson_find inside the second while loop, it could able to print out all the element by bson_print!!

Is there a bug on mongodb ?? Or my code is wrong?

Thank you very much!!!

1 Answer 1

1

Create new iterator

 bson_iterator nInterat[1];

below subit iterator

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

instead of this

bson_iterator_subobject_init(subit, sub_Object,1)

change like

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));

because your subit iterator is overwrite with current sub_object Index

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.