Search code examples
c++mongodbmongo-cxx-driver

Run aggregrate query in mongocxx as a string literal


In the mongocxx API, Collection.aggregate() expects a pipeline object in order to run an aggregate pipeline query. This means constructing the query by using the Pipeline class. Such as:

    mongocxx::pipeline p{};
    p.match(make_document(kvp("items.fruit", "banana")));
    p.sort(make_document(kvp("date", 1)));
    auto cursor = db["sales"].aggregate(p, mongocxx::options::aggregate{});

Is there a way to run an aggregate pipeline query in mongocxx by passing in a string? I'm not looking to construct the query using a mongocxx object, but running the query as a string.

For example:

    db["sales"].aggregate("[{"$match": {  ... }}"]

where "[{"$match": { ... }}" is a pipeline aggregate query of type std::string.


Solution

  • Yes you can use run_command of mongocxx::database

    bsoncxx::builder::basic::document command_document{};
    
    command_document.append(kvp(
    "eval",
    "function(username) {"
    "return db.users.findOne( { username : username } );"
    "}"));
    
    command_document.append(kvp("args", [&](sub_array child) {
    child.append(username);
    }));
    
    auto doc = db.run_command({command_document});
    

    This is a simple example of using string function with arguments to run on Mongodb by mongocxx now you can use it for any command that you want. Is this that you need ?