MongoDB $group and explicit group formation with computed column

♀尐吖头ヾ 提交于 2019-12-08 02:11:39

问题


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 } ]


来源:https://stackoverflow.com/questions/14213300/mongodb-group-and-explicit-group-formation-with-computed-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!