Watch keynotes and sessions from MongoDB.live, our virtual developer conference.

How to extract fields from change stream with C libbson

how to extract fields from mongo db change stream with C libbson

I have a bson_t “b” from a mongo db change stream which is printed like this by bson_as_canonical_extended_json :

    { "_id" : { "_data" : "825ECC4FEA0000002E2B022C0100296E5A10044A1DE2ECB8554397B8F
    03E803FB80F1F463C5F6964003C3030313330323637000004" },   
    "operationType" : "update",   
    "clusterTime" : { "$timestamp" : { "t" : 1590448106, "i" : 46 } },   
    "ns" : { "db" : "test", "coll" : "my_collection" },   
    "documentKey" : { "_id" : "00130267" },   
    "updateDescription" : { "updatedFields" : { "0x000F" : "25.006001", "0x0010" : "24.976000" },  
     "removedFields" : [  ] } }  

I can get to the “documentKey” fields like this :

    bson_iter_t iter;
    if (bson_iter_init_find(&iter, b, "documentKey"))
    bson_iter_t child;
    if (bson_iter_recurse(&iter, &child))
    {
    	while (bson_iter_next(&child))
    	{
    		const bson_value_t *value = bson_iter_value(&child);
    		printf("documentKey sub-key %s value %s\n", bson_iter_key(&child), (char*)value->value.v_utf8.str);
    	}
    }

which prints “_id” : “00130267”
how to access the array elements within the “doc” “updateDescription”, are there any examples anywhere
this structure is not of my choosing it’s from a mongo db change stream, perhaps it could be useful to others beside me

answered elsewhere : https://stackoverflow.com/questions/62050428/how-to-extract-fields-from-mongo-db-change-stream-with-c-libbson

bson_iter_t iter1;
if (bson_iter_init_find(&iter1, b, "updateDescription")) // doc 
{
    bson_iter_t child1;
    if (bson_iter_recurse(&iter1, &child1))
    {
        while (bson_iter_next(&child1))// updatedFields doc
        {
            bson_iter_t child2;
            bson_iter_recurse(&child1, &child2);
            while (bson_iter_next(&child2))
            {
                const bson_value_t *value = bson_iter_value(&child2);
                printf("updateDescription arr %s value %s\n", bson_iter_key(&child2), (char*)value->value.v_utf8.str);// key and value of the array
            }
        }
    }
}