Search code examples
c++regexmongodbmongo-cxx-driver

Mongodb c++ regex query


How to query MongoDB database using regex in c++.

mongo-cxx-driver-r3.1.1

hear is include

#include <cstdlib>
#include <iostream>
#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/uri.hpp>
#include <cstdint>
#include <vector>
#include <mongocxx/stdx.hpp>
#include <bson.h>
#include <conio.h> 
#include <sstream> 
#include <stdio.h> 
#include <string>
#include <bsoncxx/types.hpp>
#include <mongocxx/exception/exception.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>

using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::basic::kvp;
using bsoncxx::builder::basic::make_document;

here is what I have tried.

  void MyClass::on_querybtn_clicked()
   {

auto collection = conn["TestDB"]["fdevices"];
bsoncxx::types::b_regex::b_regex();//i am lost here dont know how to use it
auto cursor = collection.find({});

 for (auto doc : cursor) {

QString qstr = QString::fromStdString(bsoncxx::to_json(doc));
QJsonDocument docum = QJsonDocument::fromJson(qstr.toUtf8());
QJsonObject object = docum.object();
QString call = object["Data"].toString();
ui.mqttList->addItem(call);
}
}

Previously I build a software using Java now I am trying to build same software in Qt c++, I am new to c++.

Here is query code that I used in java for Query.

 DBObject query = new BasicDBObject();
 Pattern regex = Pattern.compile("^14-09-2017"); 
 query.put("Data", regex);

here is how my data look like. Database image


Solution

  • 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()