MongoDB $group and explicit group formation with c

2019-05-27 01:44发布

问题:

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.

回答1:

You're on the right track. In this case you need to nest $cond operators like this:

db.UM.aggregate(
    { $project: {
        computed_column: {$cond: [{$gt: ['$Salary', 30000]},
            {$cond: [{$gt: ['$Salary', 60000]}, 'Above 60K', '30K-60K']},
            'Under 30K']}
    }},
    { $group: {_id: {Salary_Slab: '$computed_column'}, count: {$sum: 1}}})

results:

[ { _id: { Salary_Slab: 'Above 60K' }, count: 3 },
  { _id: { Salary_Slab: '30K-60K' }, count: 1 },
  { _id: { Salary_Slab: 'Under 30K' }, count: 2 } ]