我的样本数据如下所示:
Category response
Privacy 1
Mobile 1
Privacy 1
Privacy 0
Phishing 1
Mobile 1
Desktop 1
Desktop 0
Security 1我为group all categories创建了一个聚合查询,并获得了如下所示的计数:
db.cmi5DashboardData.aggregate([
{$group:{_id:'$category',knt:{$sum:'$response'}}},
{$sort:{knt:-1}},
{$project:{_id:0,category:'$_id',count:'$knt'}}
])我得到的输出如下:
Category count
Privacy 2
Mobile 2
Phishing 1
Desktop 1
Security 1但是,我需要将这些数据group到下一个级别,以获得如下输出:
Category count
Privacy 2
Mobile 2
Others 3这里,假设前两个类别(具有较高计数的隐私和移动)是强的,rest所有类别都被假定为弱点,并被称为其他。Others应该是动态计算的,它是除强数据点之外的所有其他数据点的加法。
在这方面有什么建议或建议会有帮助吗?
注意:我正在使用MongoDB3.6
更新: JSON示例
{Category:'Phishing', response:1),
{Category:'Security', response:1),
{Category:'Privacy', response:1),
{Category:'Privacy', response:1),
{Category:'Privacy', response:0),
{Category:'Mobile', response:1),
{Category:'Mobile', response:1),
{Category:'Desktop', response:1),
{Category:'Desktop', response:0),发布于 2018-05-15 10:17:28
您应该尝试$facet聚合来获得所需的结果,这对于limit和skip来说非常简单.
您可以检查输出here。
db.collection.aggregate([
{ "$facet": {
"top": [
{ "$group": {
"_id": "$Category",
"response": { "$sum": "$response" }
}},
{ "$sort": { "response": -1 }},
{ "$limit": 2 }
],
"rest": [
{ "$group": {
"_id": "$Category",
"response": { "$sum": "$response" }
}},
{ "$sort": { "response": -1 }},
{ "$skip": 2 },
{ "$group": {
"_id": "Others",
"response": { "$sum": "$response" }
}}
]
}},
{ "$project": { "data": { "$concatArrays": ["$top", "$rest"] }}},
{ "$unwind": "$data" },
{ "$replaceRoot": { "newRoot": "$data" }}
])https://stackoverflow.com/questions/50294184
复制相似问题