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
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!" }
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.