Search code examples
c#databasemongodb.net-coreaggregate

MongoDB group by ranges on multiple fields


I have the following docs in my DB:

{
  Age : 10,
  BPM : 20,
  Price: 6
},
{
  Age : 12,
  BPM : 30,
  Price: 9
},
{
  Age : 15,
  BPM : 40,
  Price: 6
},
{
  Age : 10,
  BPM : 46,
  Price: 7
},
{
  Age : 20,
  BPM : 60,
  Price: 8
}

I need help to write an aggregate query to find out for groups (age range 10-15 & BPM 20-50), (age range 15 - 20 & BPM 40 - 90), What is the total sum of prices for each group of ranges. There can be few more groups of ranges.


Solution

  • When you have multiple conditions, one option is to use $switch:

    db.collection.aggregate([
      {$set: {
          group: {$switch: {
              branches: [
                {case: {
                    $and: [
                      {$gte: ["$Age", 10]},
                      {$lt: ["$Age", 15]},
                      {$gte: ["$BPM", 20]},
                      {$lt: ["$BPM", 50]}
                    ]
                }, then: 1},
                {case: {
                    $and: [
                      {$gte: ["$Age", 15]},
                      {$lt: ["$Age", 20]},
                      {$gte: ["$BPM", 40]},
                      {$lt: ["$BPM", 90]}
                    ]
                }, then: 2}
              ],
              default: "Did not match"
          }}
      }},
      {$group: {_id: "$group", totalSumOfPrices: {$sum: "$Price"}}}
    ])
    

    See how it works on the playground example