BSONObj obj = BSONObjBuilder().append("name", "John").append("age", 30).obj(); BSONObj address = BSONObjBuilder() .append("street", "123 Main St.") .append("city", "New York") .append("state", "NY") .obj(); BSONObj newObj = BSONObjBuilder(obj) .append("address", address) .obj(); BSONObj retrievedAddress = newObj.getObjectField("address");
bsoncxx::document::value doc_value = bsoncxx::builder::basic::make_document( kvp("name", "John"), kvp("array", bsoncxx::builder::basic::make_array( "item 1", "item 2", "item 3" )) ); bsoncxx::document::view view{doc_value.view()}; bsoncxx::document::element elem = view["array"]; bsoncxx::array::view sub_view{elem.get_array().value}; bsoncxx::document::view sub_elem = sub_view[2].get_document().value; bsoncxx::document::element string_elem = sub_elem["string_field"]; std::string str = string_elem.get_utf8().value.to_string();In this example, a BSON document is created using the `bsoncxx` library. The `getElement` method is used to retrieve an array field named `array`. A sub-view of the array is obtained, and its third element is retrieved as a document view. A string field named `string_field` is then retrieved from this document view and converted to a `std::string`. This code uses the MongoDB C++ driver library.