Mongodb c++ regex query Mongodb c++ regex query mongodb mongodb

Mongodb c++ regex query


Use some builders and make the document, providing the string input for the pattern:

#include <bsoncxx/builder/basic/document.hpp>#include <bsoncxx/builder/basic/kvp.hpp>using bsoncxx::builder::basic::kvp;using bsoncxx::builder::basic::make_document;auto cursor = collection.find(make_document(  kvp("Data", bsoncxx::types::b_regex{"^14-09-2017"})));

A bit easier to read than stream builder IMHO, but the basic premise is there. Still a string for input, much like Pattern.compile()


I've tried several approaches but finally I came up with the most straightforward one. I build a query as a json and then convert is to bson using bsoncxx::from_json function.a working piece of code looks like:

 mongocxx::instance instance{}; mongocxx::uri uri("mongodb://localhost:27017"); mongocxx::client *m_c = new mongocxx::client(uri);     std::string query = "{\"name.firstName\": {\"$options\": \"i\",\"$regex\": \"^pattern\"}}"; bsoncxx::builder::stream::document doc; //this one to define q not inside try catch block. bsoncxx::document::value q(doc.view()); try{   q = bsoncxx::from_json(query); }catch (bsoncxx::exception &e){    std::cerr<<"error: "<<e.code()<<" "<<e.what();    return; } mongocxx::options::find opt; mongocxx::cursor cursor = m_c->database("db_name").collection("collection_name").find( std::move(q), opt);

An important thing here is that I could not use q as bsoncxx::document::view. Because a value for this view is created inside try - catch block, till the timewhen the control flow came to the find function bsoncxx::document::view q was always empty. So I had to use bsoncxx::document::value q and move semantics in the find function.


#include <bsoncxx/builder/basic/document.hpp>#include <bsoncxx/builder/basic/kvp.hpp>using bsoncxx::builder::basic::kvp;using bsoncxx::builder::basic::make_document;auto cursor =  collection.find(make_document(kvp("field",make_document(kvp("$regex":"pattern"),kvp("$options","i"))));

Refer To Official