gpt4 book ai didi

c++ - 具有唯一元素和最大值(value)的 MongoDb 查询

转载 作者:可可西里 更新时间:2023-11-01 10:25:05 27 4
gpt4 key购买 nike

我正在使用遗留的 c++ 驱动程序访问 MongoDB,目前我正在努力查询这些元素的集合

{
id: 1,
progress: 0.3456
}

相同 ID 有数千个重复条目,但我只想要一组具有唯一 ID 值和每个 ID 的最大进度值(或最低,或小于特定值)。我可以在单个查询中执行此操作吗?

因此每个 id 只出现一次但具有特定的进度属性(例如最大进度)

谢谢

最佳答案

您可以使用 aggregation framework 来实现这一点。您的管道将是

var pipeline = [
{
"$group": {
"_id": "id",
"lowest": { "$min": "$progress" },
"greatest": { "$max": "$progress" },
"count": { "$sum": 1 }
}
},
{
"$match": { "count": 1 }
}
]

db.collection.aggregate(pipeline);

在 C++ 中,您可以调用此 aggregation 通过采用数据库名称和包含命令和集合的 BSONObj 的“runCommand”方法,加上作为数组的实际管道。最后一个参数是响应对象。您可以阅读完整文档 here .

例如,假设您有一个DBClientConnection 连接到一个test 数据库和一个集合“jobs”,您可以按以下方式运行上述聚合操作:

DBClientConnection conn;
BSONObj res;

BSONArray pipeline = BSON_ARRAY(
BSON("$group" <<
BSON("_id" << "$id" ) <<
BSON("lowest" <<
BSON("$min" << "$progress")
)
)
);

BSONArray pipeline = BSON_ARRAY(
BSON("$group" <<
BSON("_id" << "$id" <<
"lowest_progress" << BSON("$min" << "$progress") <<
"greatest_progress" << BSON("$min" << "$progress") <<
"count" << BSON("$sum" << 1)
)
) <<
BSON("$match" <<
BSON("count" << 1)
)
);

conn.runCommand( "test", BSON( "aggregate" << "jobs" << "pipeline" << pipeline ), res );

cout << res.toString() << endl

关于c++ - 具有唯一元素和最大值(value)的 MongoDb 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34807119/

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