mongodb - monogdb 中的 $facet 聚合
问题描述
我的示例数据如下所示:
Category response
Privacy 1
Mobile 1
Privacy 1
Privacy 0
Phishing 1
Mobile 1
Desktop 1
Desktop 0
Security 1
我为group
所有人创建了一个聚合查询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
在这里,前两个类别(具有较高计数,即隐私和移动)被假定为强,其余所有类别都被假定为弱点并称为其他。Others
应该动态计算,这是除了强数据点之外的所有其他数据点的添加。
关于此的任何建议或指示可能会有所帮助?
注意:我使用的是 mongodb 3.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),
解决方案
您应该尝试$facet
聚合以获得所需的结果,该结果使用起来非常简单,limit
并且skip
...
您可以在此处检查输出
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" }}
])
推荐阅读
- django - Django REST Serializer 使用错误的模型进行序列化
- python - python文件写入程序运行时如何更新桌面上的文件大小
- javascript - 使用 d3.js 更新表数据
- c# - C#捕获从不在进程中的函数返回的异常?
- r - 如何设置仅在输入 3 时才显示集合向量的函数?
- javascript - 如果 URI 没有改变,例如在单页应用程序上,如何检测用户是否在新页面上?
- angular - Angular Kendo UI 全局访问
- php - 内连接循环通过
- git - 如何 git rebase 从另一个分支直接到 master 分支?
- javascript - 受控数字比例映射