I am using mongo c driver 1.1 with mongo version 3.0. Libbson version 1.1. I am using an iterator to look for certain fields in a document. The following code only works when "fieldA" is above "fieldB" in mongodb. If i change the order bson_iter_find returns false.
if(bson_iter_find(&iterator,"fieldA")){
pintf("fieldA");
}
if(bson_iter_find(&iterator,"fieldB")){
pintf("fieldB");
}
In older versions of the libbson(0.4) I was able to use bson_find(), to look for fields in a doc. Is there something similar i can use in the new libbson library?
Link to new libbson library https://api.mongodb.org/libbson/current/
to directly answer your question, you should call bson_iter_init (http://api.mongodb.org/libbson/current/bson_iter_init.html) for every single "new" query you're making against the data.
Presumably you have a single bson_iter_init call on a bson_t object. You just need another.
bson_iter_t iterator1;
bson_iter_t iterator2;
if (bson_iter_init (&iterator1, doc) &&
bson_iter_find (&iterator1, "fieldA") ) {
//Do something with fieldA
}
if (bson_iter_init (&iterator2, doc) &&
bson_iter_find (&iterator2, "fieldB") ) {
//Do something with fieldB
}
bson_free(doc); //DONT FORGET TO DESTROY THE BSON_T object at the end.
or, just use the combined command bson_iter_init_find (http://api.mongodb.org/libbson/current/bson_iter_init_find.html) if you don't want to deal with the internals.
bson_iter_t iterator1;
bson_iter_t iterator2;
if (bson_iter_init_find (&iterator1, doc, "fieldA") ) {
//Do something with fieldA
}
if (bson_iter_init_find (&iterator2, doc,"fieldB") ) {
//Do something with fieldB
}
bson_free(doc); //DONT FORGET TO DESTROY THE BSON_T object at the end.
If you're interested in why, I work on the bsonsearch (https://github.com/bauman/bsonsearch) library and have similar problems.
Be very cautious on how you're dealing with pointers. Nearly everything under the hood in libbson is manipulating pointers to an area in memory.
The reason ordering maters is because you initialized once, when you called iter_find, libbson would seek past B to locate A. The subsequent call to find B would seek to the end of the buffer and miss it. You avoid that problem by reinitializing the iterator back to position 0 and start the seek from there.
Unless you know exactly what you're doing and want to optimize seeks around the buffer, it's probably best to just reinitialize the iterator for every find.