How to add fields to bson in MongoDB C driver (not all at once though)

For appending to bulk write in order to update existing fields within a doc, I can’t do it all in place, I need to call an append function repeatedly as data becomes available, thanks for any hints, I am clueless how to do it ?

void appendfn(bson_t* doc, char * name, char* value)
{
char *str;
bson_t child;

bson_append_document_begin (doc, "$set", -1, &child);
BSON_APPEND_UTF8(&child, name, value);
bson_append_document_end (doc, &child);

str=bson_as_canonical_extended_json (doc, NULL);
printf("%s\n",str);

}

bson_t doc=BSON_INITIALIZER; appendfn(&doc,“f1”,“f1v”) yields : { “$set” : { “f1” : “f1v” } }

if I call it again appendfn(&doc,“f2”,“f2v”) :

{ “$set” : { “f1” : “f1v” }, “$set” : { “f2” : “f2v” } }

but I need :

{ “$set” : { “f1” : “f1v”, “f2” : “f2v” } }

for argument’s sake I could do something of the sort (from a single thread) :

    void appendmore(bson_t* doc, char * name, char* value) 
    {
        char *str;
        static bson_t *child=NULL;// static is only for single thread obviously, need thread local storage for multiple threads
    
        if(!child)
        {
            child=bson_new ();
            bson_append_document_begin (doc, "$set", -1, child);
        }
        if(name)
        {
            BSON_APPEND_UTF8(child, name, value);
            str=bson_as_canonical_extended_json (child, NULL);
            printf("child %s\n",str);
        }
        else
            bson_append_document_end (doc, child);
    }

appendmore(&doc,"f1","f1v");
appendmore(&doc,"f2","f2v");
appendmore(&doc,NULL,NULL);

but surely there must be a way to continue adding fields in an “opened” child ? i.e. to reopen it somehow ?

another thing I can’t understand, with latest 1.19 c driver, child seems cannot be allocated with new, it must be static because it gets flagged as BSON_FLAG_NO_FREE