在mongocxx中将聚合查询作为字符串字面量运行

3
在mongocxx API中,Collection.aggregate()需要一个流水线对象才能运行聚合管道查询。这意味着要使用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的管道聚合查询。


你想问的是,你可以将一个字符串解析成bson文档而不是逐步构建它吗? - rustyx
是的,我希望将整个查询作为字符串,以便可以使用mongocxx运行。 - anon9928175234
你可以使用 bsoncxx::from_json 将管道组件(如匹配、排序等)解析为 JSON 片段,而不是整个字符串。 - rustyx
不,目前没有构建这样一个东西的方法。但是添加它可能非常容易。你介意提交一个工单吗?https://jira.mongodb.org/projects/CXX - acm
1个回答

1

是的,您可以使用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上运行的简单示例,现在您可以将其用于任何您想要的命令。

这符合您的需求吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接