在mongocxx中将aggregrate查询作为字符串文字运行

时间:2018-08-17 17:49:37

标签: c++ mongodb mongo-cxx-driver

在mongocxx API中,Collection.aggregate()需要管道对象才能运行aggregate pipeline查询。这意味着使用Pipeline类构造查询。如:

    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{});

是否可以通过传入字符串在mongocxx中运行聚合管道查询?我不是要使用mongocxx对象构造查询,而是将查询作为字符串运行。

例如:

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

其中“ [[{$$ match“:{...}}”是类型为std :: string的管道聚合查询。

1 个答案:

答案 0 :(得分:0)

是的,您可以使用mongocxx::database的run_command

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});

这是一个简单的示例,该示例使用mongocxx在Mongodb上运行带有参数的字符串函数,现在您可以将其用于所需的任何命令。 这是您需要的吗?