consider the mongo document: {"key1": "value1", "key2": {"subkey1": "subvalue1"}}
, this can be encoded (using python bson module like: bson.encode(DATA)) to the following uint8_t array: [56, 0, 0, 0, 2, 107, 101, 121, 49, 0, 7, 0, 0, 0, 118, 97, 108, 117, 101, 49, 0, 3, 107, 101, 121, 50, 0, 28, 0, 0, 0, 2, 115, 117, 98, 107, 101, 121, 49, 0, 10, 0, 0, 0, 115, 117, 98, 118, 97, 108, 117, 101, 49, 0, 0, 0]
. Now, I use this array to initialize the bson_t struct and use the iterator to find the subdocument for key2
.
Here I want to create another bson_t document from this. I tried using the bson_iter_document() method but it gives me precondition failed: document
error. Maybe i'm not using it right. Is there another way to do it properly?
void test_bson(){
uint8_t raw[] = {56, 0, 0, 0, 2, 107, 101, 121, 49, 0, 7, 0, 0, 0, 118, 97, 108, 117, 101, 49, 0, 3, 107, 101, 121, 50, 0, 28, 0, 0, 0, 2, 115, 117, 98, 107, 101, 121, 49, 0, 10, 0, 0, 0, 115, 117, 98, 118, 97, 108, 117, 101, 49, 0, 0, 0};
bson_t *bson;
bson = bson_new_from_data(raw, 56);
bson_iter_t iter;
bson_iter_init(&iter, bson);
if (bson_iter_find(&iter, "key2")){
printf("found. %d\n", bson_iter_type(&iter));
const uint8_t **subdocument;
uint32_t subdoclen = 56;
bson_iter_document (&iter, &subdoclen, subdocument);
}
bson_free(bson);
}