问题
My Sample data looks like below:
Category response
Privacy 1
Mobile 1
Privacy 1
Privacy 0
Phishing 1
Mobile 1
Desktop 1
Desktop 0
Security 1
I have created an aggregate query to group
all categories
and get the count as below:
db.cmi5DashboardData.aggregate([
{$group:{_id:'$category',knt:{$sum:'$response'}}},
{$sort:{knt:-1}},
{$project:{_id:0,category:'$_id',count:'$knt'}}
])
I get the output as below:
Category count
Privacy 2
Mobile 2
Phishing 1
Desktop 1
Security 1
However, I need to group
this data to next level to get the output as below:
Category count
Privacy 2
Mobile 2
Others 3
Here, first two categories(with higher count i.e. Privacy & Mobile) are assumed as strong and rest all categories are assumed as weak points and termed as others . Others
should be calculated dynamically which is an addition of all other data points except strong data points.
Any suggestions or pointers on this could be helpful?
Note: I'm using mongodb 3.6
Update: JSON Samples
{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),
回答1:
You should try $facet
aggregation to get the desired result which pretty simple to use with limit
and skip
...
You can check the output 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/facet-aggregation-in-monogdb