#include#include #include #include #include #include #include using bsoncxx::builder::stream::document; using bsoncxx::builder::stream::finalize; using bsoncxx::builder::stream::open_document; using bsoncxx::builder::stream::close_document; using bsoncxx::types::b_int32; mongocxx::instance inst{}; mongocxx::pool pool{mongocxx::uri{}, mongocxx::pool::options{}}; void update_document(mongocxx::pool::entry entry) { auto client = std::move(entry.client()); auto coll = client["mydb"]["mycoll"]; auto query = document{} << "field1" << "value1" << finalize; auto projection = document{} << "field2" << 1 << finalize; auto result = coll.find_one(query.view(), mongocxx::options::find{}.projection(projection.view())); if (!result) return; auto doc_copy = result->to ().copy(); doc_copy["field2"] = b_int32(42); coll.update_one(query.view(), document{} << "$set" << open_document << "field2" << b_int32(42) << close_document << finalize); } int main() { auto entry = pool.acquire(); update_document(entry); return 0; }
#includeIn this example, we first create a BSON object representing a document with name, age, and address fields. We then make a copy of this BSON object using the `copy` function. We add a new field to the copied BSON object using the `append` function. Finally, we print the JSON representation of the BSON object using the `to_json` function. This example requires the use of the BSON library in the MongoDB C++ driver.#include #include #include #include using bsoncxx::builder::stream::document; using bsoncxx::builder::stream::finalize; using bsoncxx::builder::stream::open_document; using bsoncxx::builder::stream::close_document; using bsoncxx::builder::stream::array; using bsoncxx::builder::stream::close_array; int main() { bsoncxx::document::value doc_value = document{} << "name" << "John Doe" << "age" << 42 << "address" << open_document << "street" << "123 Main St" << "city" << "Anytown" << "state" << "CA" << "zip" << "12345" << close_document << finalize; BSONObj bson_obj = doc_value.view(); BSONObj bson_obj_copy = bson_obj.copy(); bson_obj_copy = bson_obj_copy.append("id", bsoncxx::oid{}.to_string()); std::cout << bsoncxx::to_json(bson_obj_copy.view()) << std::endl; return 0; }