Conditional Operator in MongoDb

Conditional operator if-condition 

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 to identify which student is pass(>=3)  or fail(<3).

 
db.people.aggregate([
    {$match:{"school":"MathHighSchool"}},
    {$project:{"school":1,"div": {$cond:{ if:{ $gte:["$grade",3]},then:"pass",else:"fail"}}}}
    ]);
    

Output: 

[
        "_id" : ObjectId("6024b764abea6cc5c99ceefd")
        "school" : "MathHighSchool"
        "div" : "pass"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceefe")
        "school" : "MathHighSchool"
        "div" : "pass"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceeff")
        "school" : "MathHighSchool"
        "div" : "pass"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef00")
        "school" : "MathHighSchool"
        "div" : "pass"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef01")
        "school" : "MathHighSchool"
        "div" : "fail"
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef02")
        "school" : "MathHighSchool"
        "div" : "pass"
    }
      
]


No comments:

Post a Comment