mongodb - Mongodb - 按值分组并获取计数
问题描述
我有一个聚合查询,它返回类似的结果
{
count:1,
status: 'FAILED',
article_id: 1
},
{
count:1,
status: 'DELIVERED',
article_id: 1
}
我想按 article_id 分组并根据 status 获取计数,如下所示:
{
article_id:1,
FAILED:1,
DELIVERED:2
}
我该如何存档?提前致谢。
解决方案
其他答案原则上可能有效,但它们仅限于硬编码为 statusFAILED
和DELIVERED
.
如果您想为任意状态提供通用解决方案,您可以使用这个:
db.collection.aggregate([
{ $set: { data: [{ k: "$status", v: "$count" }] } },
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
{ $arrayToObject: "$data" }, { article_id: "$article_id" }
]
}
}
},
{
$group: {
_id: "$article_id",
status: { $push: "$$ROOT" }
}
},
{ $set: { status: { $mergeObjects: ["$status"] } } },
{ $replaceRoot: { newRoot: "$status" } },
])
推荐阅读
- python - 如何将数据框中图像的扩展名转换为大写
- elasticsearch - 如何在elasticsearch7中获取索引的项目数?
- azure-cosmosdb - 如何在 cosmos db 中使用 join 来获取结果
- r - r 按百分比用颜色填充地图
- javascript - 如何使用 WebRTC 将视频流式传输到 RTMP?
- tensorflow - Tensorflow:如何从模型图中获取输入和输出节点?
- mysql - 结果集的排序
- python - 如何在不加倍代码的情况下重用小部件?
- spring - 在 Spring Cloud Config 中使用 @PropertySource - Git
- node.js - 获取模型后获取关联模型