Switch conditional operator in mongodb

Write a Switch operator in Mongo

Example:

[{ 
        "_id" : ObjectId("6024b764abea6cc5c99ceefd"), 
        "name" : "George", 
        "grade" : 5.0, 
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceefe"), 
        "name" : "John", 
        "grade" : 4.0, 
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceeff"), 
        "name" : "Paul", 
        "grade" : 3.0, 
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef00"), 
        "name" : "Ringo", 
        "grade" : 5.0, 
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef01"), 
        "name" : "Johnny", 
        "grade" : 2.0, 
        "school" : "MathHighSchool"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef02"), 
        "name" : "Joshua", 
        "grade" : 7.0, 
        "school" : "MathHighSchool"
    }


]

Approach

Query: Query that finds all people who: study in the MathHighSchool and then group them by their grades, as it shows the number of people with grade <3 number of people with grade between 3 and 5 and number of people with grade > 5.

 
db.people.aggregate([
    {$match:{"school":"MathHighSchool"}},
    {$project:{"school":1,"div": { $switch:
                {
                  branches: [
                    {
                      case: { $lte : ["$grade", 3 ] },
                      then: "less than or equal to 3"
                    },
                    {
                      case: { $and : [ { $gt : ["$grade", 3 ] },
                                       { $lt : [ "$grade", 5 ] } ] },
                      then: "between 3 and 5"
                    },
                    {
                      case: { $gte : [ "$grade", 5] },
                      then: "greater than or equal to 5"
                    }
                  ],
                }}}},
                {$group:{"_id":"$div","count":{$sum:1}}}
    ]);

    

Output: 

[
    { 
        "_id" : "between 3 and 5", 
        "count" : 1.0
    }
    { 
        "_id" : "less than or equal to 3", 
        "count" : 2.0
    }
    { 
        "_id" : "greater than or equal to 5", 
        "count" : 3.0
    }
      
]


No comments:

Post a Comment