BSONObj obj = BSONObjBuilder().append("name", "John").obj(); BSONElement elem = obj.getField("name"); const char* name = elem.valueStringData(); std::cout << name << std::endl; // outputs "John"
BSONObj oldObj = BSONObjBuilder().append("name", "John").obj(); BSONElement oldElem = oldObj.getField("name"); const char* oldName = oldElem.valueStringData(); BSONObjBuilder builder; if (strcmp(oldName, "John") == 0) { builder.append("name", "Jane"); } else { builder.append("name", "John"); } BSONObj newObj = builder.obj();In this example, we first retrieve the string value of a BSON element, then modify it and build a new BSON object with the updated value. These examples use the C++ driver for MongoDB, which is part of the official MongoDB C++ driver package.