BSONObjBuilder builder; builder.appendRegex("email", "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$"); BSONObj bsonObj = builder.obj(); std::cout << bsonObj.toString() << std::endl;
{ "email" : { "$regex" : "^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$" } }
#includeIn this example, we use the MongoDB C++ driver library to create a search query for finding documents in the `testcollection` collection of the `testdb` database which has a name containing the string `John`, case-insensitively. The search query uses the `$regex` operator, and the `appendRegex` method is not used here, but the concept is the same, i.e., to create a BSON object with a regular expression value for querying the database. Package/library: MongoDB C++ Driver (mongocxx) and BSONCPP.#include #include #include mongocxx::instance instance{}; // Initialize MongoDB driver instance mongocxx::client client{mongocxx::uri{}}; // Connect to MongoDB server bsoncxx::builder::basic::document search_query; search_query.append(bsoncxx::builder::basic::kvp("name", bsoncxx::builder::basic::make_document( bsoncxx::builder::basic::kvp("$regex", "John"), bsoncxx::builder::basic::kvp("$options", "i")))); mongocxx::collection coll = client["testdb"]["testcollection"]; auto cursor = coll.find(search_query.view()); // Execute query and get cursor for results for (auto& doc : cursor) { std::cout << bsoncxx::to_json(doc) << std::endl; }