Consider this code in SQL that forms groups based on a range of salary:
;With TableWithComputedColumn as
(
select
computedcolumn =
Case
when Salary<30000 then 'Under 30K'
when Salary>30000 and Salary<60000 then '30K-60K'
else 'Above 60K'
end
from Tbl_UserMaster
)
select computedcolumn, COUNT(*)
from TableWithComputedColumn
group by computedcolumn
I want to do this in Mongo.. My guess is that the CTE part will require me to first output {computed column}
to a temporary collection and then do a $group
on that collection. Another way (and the one I prefer) could be to use $project
to project {computed column}
as the first stream in the
aggregation pipeline and then perform $group
.
db.UM.aggregate(
{$project: { "computed_column": { //something with $cond}} },
{$group: {_id: {Salary_Slab:"$computed_column"}, count: {$sum:1}}}
);
Please also go through a similar question I had asked before:
Conditional $sum in MongoDB
It basically gives me a pivoted output. In this situation, I need unpivoted output. To compare the two, the answer to the other question will create three columns:{Under 30K, 30K-60K, Above 60K} with a single row of counts, whereas I need three rows for Under 30K, 30K-60K, and Above 60K in one column and their respective counts in the second column.