I am running the following query on a dataset with one billion records. The query becomes significantly slower when I add a sort by userId. The execution time increases drastically. Can anyone guide me on how to optimize this query for better performance?
[
{
"$group": {
"_id": "$userId",
"totalMonthly": { $sum: { $cond: [{ "$eq": ["$subscriptionType", "month"] }, 1, 0] } },
"subscriptionAmt": { $sum: "$subscriptionAmt" },
"subscriptionId": {
"$first": "$subscriptionId"
}
}
},
{
"$sort": { "totalMonthly": -1 }
},
{
"$limit": 5
}
]