Home > OS >  Building a BSON filter from raw query string
Building a BSON filter from raw query string

Time:09-20

Is it possible to create a collection filter from a raw query string? If so, how?

I'm using the mongocxx driver and want to use some tested queries from the mongo shell instead of building them inconveniently with that BSONCXX streambuilder. But I can not find any examples.

I tried to convert from_json(), but this throws an error

bsoncxx::from_json("{ \"val\": { $gt: 0, $lt: 9 }}");
Got parse error at "$", position 11: "SPECIAL_EXPECTED": could not parse JSON document

whereby

bsoncxx::from_json("{ \"val\": { \"$gt\": 0, \"$lt\": 9}}");

is leading to an unrecoverable exception and crashes the application.

CodePudding user response:

Actually

bsoncxx::from_json("{ \"val\": { \"$gt\": 0, \"$lt\": 9}}");

was not the issue. The transformation from std::string to bsoncxx::view was. Not 100% sure where the reason for the crash was, but this does the trick for me.

Solution:

std::string query( R"( { "val": { "$gt": 0, "$lt": 9}} )");
collection.find(bsoncxx::from_json(query.c_str()).view());
  • Related