When To Switch in MongoDB

Posted By : Arun Kataria | 28-Feb-2018

In MongoDB 3.4 the $switch operator to perform the multi-switch statement in a $project stage. Calculate a list of case expression. It find the expression which checks to true, A $switch executes the specified statement are break out of a control flow.

A $switch has a syntax:

$switch: {
   branches: [
      { case: 'expression', then: 'expression' },
      { case: 'expression', then: 'expression' },
      ...
   ],
   default: 
}
        

branches : It will only contain the object with case and then key.
case and then: Case can be any valid value that will return boolean value. Then will execute if case return true value.
dafault: It is optional, it will execute if no case expression return to true.

For example:
User collection:

{ "_id" : 1, "name" : "a", "scores" : [ 87, 86, 76 ] }
{ "_id" : 2, "name" : "b", "scores" : [ 71, 64, 82 ] }
{ "_id" : 3, "name" : "c", "scores" : [ 91, 84, 97 ] }
        

Querry

db.user.aggregate( [
  {
    $project:
      {
        "name" : 1,
        "summary" :
        {
          $switch:
            {
              branches: [
                {
                  case: { '$gte' : [ { '$avg' : "$scores" }, 90 ] },
                  then: "Doing great!"
                },
                {
                  case: { $and : [ { '$gte' : [ { '$avg' : "$scores" }, 81 ] },
                                   { $lt : [ { '$avg' : "$scores" }, 90 ] } ] },
                  then: "Doing pretty well."
                },
                {
                  case: { '$lt' : [ { '$avg' : "$scores" }, 81 ] },
                  then: "Needs improvement."
                }
              ],
              default: "No scores found."
            }
         }
      }
   }
] );
        

Result

{ "_id" : 1, "name" : "a", "summary" : "Doing pretty well." }
{ "_id" : 2, "name" : "b", "summary" : "Needs improvement." }
{ "_id" : 3, "name" : "c", "summary" : "Doing great!" }
        

 

About Author

Author Image
Arun Kataria

Arun has good skills in AngularJS, NodeJS, MongoDB and many more. He is highly motivated which allow him to strive for proficiency when accomplishing assigned duties. He is an excellent team operative.

Request for Proposal

Name is required

Comment is required

Sending message..