MongoDB rename boundary values for output

Viewed 46

I have this query to display people in certain age groups.

db.people.aggregate([
    {
      $bucket: {
        groupBy: "$age",
        boundaries: [ 0, 10, 20,  30, Number.POSITIVE_INFINITY ],
        default: Number.NEGATIVE_INFINITY,
        output: {
          "count": { $sum: 1 }
        }
      }
    }
  ])
enter code here

which produces following output:

{ "_id" : 0, "count" : 5 }
{ "_id" : 10, "count" : 10 }
{ "_id" : 20, "count" : 6 }
{ "_id" : 30, "count" : 9 }

I want to display it as

{ "_id" : 0, "count" : 5 }
{ "_id" : 10, "count" : 10 }
{ "_id" : 20, "count" : 6 }
{ "_id" : ">30", "count" : 9 }

How can I make it? Thanks.

1 Answers

There's no hacky way this make this happen, you'll have to add a $project stage and specify the logic you want, like so:


db.people.aggregate([
    {
        $bucket: {
            groupBy: "$age",
            boundaries: [ 0, 10, 20,  30, Number.POSITIVE_INFINITY ],
            default: Number.NEGATIVE_INFINITY,
            output: {
                "count": { $sum: 1 }
            }
        }
    },
    {
        $project: {
            _id: {
                $cond: [{$eq: ['$_id', 30]}, '>30', '$_id']
            },
            count: 1
        }
    }
])
Related