skip to Main Content

I have the following docs in my collection –

{
  name: 'test1',
  score: 80
},
{
  name: 'test2',
  score: 50
},
{
  name: 'test3',
  score: 100
},
{
  name: 'test4',
  score: 70
}

I would like to aggregate and group those docs, based on scores ranges – 0-60, 61-90, 91-100

so the results will look like –

{
  score: '0-60',
  tests: ['test2']
}, 
{
  score: '61-90',
  tests: ['test1', 'test4']
}, 
{
  score: '91-100',
  tests: ['test3']
}

Can I somehow group values by ranges in MongoDB?

2

Answers


  1. db.collection.aggregate([
      {
        $addFields: {
          range: {//Create customised ranges
            $switch: {
              branches: [
                {
                  case: {
                    $lte: [
                      "$score",
                      60
                    ]
                  },
                  then: "0-60"
                },
                {
                  case: {
                    $lte: [
                      "$score",
                      90
                    ]
                  },
                  then: "61-90"
                },
                {
                  case: {
                    $lte: [
                      "$score",
                      100
                    ]
                  },
                  then: "91-100"
                }
              ],
              default: "invalid"
            }
          }
        }
      },
      {
        "$group": {//Group on the range
          "_id": "$range",
          "tests": {
            "$push": "$name"
          }
        }
      }
    ])
    

    playground

    Login or Signup to reply.
  2. You may check also the $bucketAuto aggregation operator which allow you to auto group by range based on number of ranges:

    db.collection.aggregate([
      {
        $bucketAuto: {
         groupBy: "$score",
         buckets: 3
        }
      }
    ])
    

    Explained: You provide the field in groupBy by which you need to group and you provide the number of ranges.

    Playground

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search