cmongodbmongodb-c

MongoDB c Driver extracting arrays from bson


I am attempting to extract an array from a MongoDB document using the c driver. The document is structured like this:

name: "TestName"
data:["testData1","testData2"];

I have retrieved the document like this:

cursor = mongoc_collection_find_with_opts(collection, query, NULL, NULL);

while (mongoc_cursor_next(cursor, &document))
{
    str = (const unsigned char *)bson_as_canonical_extended_json(document, NULL);
    b = bson_new_from_json(str, -1, &error);
}

if (bson_iter_init(&iter, b))
{
    while (bson_iter_next(&iter))
    {
       //if the type is an array
        if (bson_iter_type(&iter) == 4){
            //requesting for data
            bson_iter_find(&iter, "data");
            const uint8_t * data = NULL;
            uint32_t len = 0;
            bson_iter_array(&iter, &len, &data);
            bson_t *dataArray = bson_new_from_data(data, len);
            bson_iter_t dataIter;
            bson_iter_init(&dataIter, dataArray);
            bson_iter_find(&dataIter, "0");
        }
    }
}

The debugger shows a failure at bson_iter_array(). I have referenced this post and have not been able to resolve this issue. How can I correctly retrieve and store the data from an array from MongoDB using the c driver?


Solution

  • mongoc_cursor_next gives you a bson_t pointer which is the whole document.

    From here use the documentation to iterate that document.

    This section covers descending into a hash key (data in your example) and it looks like the same code would be used for an array field to get down to the array elements.

    Once you are at the array level, use http://mongoc.org/libbson/current/bson_iter_utf8.html to retrieve the string elements.

    You should not be converting to or from json or extended json or creating any new bson_t instances.