gpt4 book ai didi

c++ - 在 mongocxx 中将聚合查询作为字符串文字运行

转载 作者:可可西里 更新时间:2023-11-01 09:53:50 27 4
gpt4 key购买 nike

在 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 类型的管道聚合查询。

最佳答案

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

关于c++ - 在 mongocxx 中将聚合查询作为字符串文字运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51900630/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com