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

How to access array elements from document using bsoncxx

I retrieve the following document from a mongoDB query.
I would like to access the values in the array within the “profile” key value pair, however i cannot figure out from the documentation how to do this.

the document I get back from the mongodb query is:

{ “_id” : { “$oid” : “5ef5fd085e27211f15d8f842” }, “username” : “arif”, “password” : “aspass”, “designer” : true, “status” : “active”, “profile” : [ { “FunctionalArea” : “creditRisk”, “AuthLevel” : 3 }, { “FunctionalArea” : “frontOffice”, “AuthLevel” : 1 } ] }

in the above json structure, the key: “profile” contains a list of json objects. it is the elements in the json object that i would like to retrieve, i.e. FunctionalArea: frontOffice etc.

so far I have tried to do the following:

auto cursor = collection.find(queryDoc.view());
for (auto doc : cursor) {
bsoncxx::types::b_array profile=doc[“profile”].get_array();

up to this point, the code works fine, however i am now unable to figure out how to access the elements in the json objects contained in the array.

Any help would be greatly appreciated.

Hi @arif_saeed,

To inspect the array, you can retrieve the elements as bsoncxx::document::element which then you can inspect further. For example:

for (auto doc : cursor) {
    bsoncxx::document::element profiles = doc["profile"];
    if (profiles && profiles.type() == bsoncxx::type::k_array){
        bsoncxx::array::view profile{profiles.get_array().value};
        for (bsoncxx::array::element subdocument : profile){
            std::cout<< subdocument["FunctionalArea"].get_utf8().value << std::endl;
        }
    }
}

Regards,
Wan

2 Likes