Arithmetic $divide operator in mongo

Write a query in mongo to use of $divide 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 to divide by 2  in grade when grade >=5.

db.getCollection("people").aggregate([
      {$match:{ "school" : "MathHighSchool"}},
      {$project:{"name":1,"grade":{$cond:{if:{$gte:["$grade",5]},then:{$divide:["$grade",2]},else:"$grade"}}}}
      
      ]);
    

Output: 

[
   

      { 
        "_id" : ObjectId("6024b764abea6cc5c99ceefd")
        "name" : "George"
        "grade" : 1.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceefe")
        "name" : "John"
        "grade" : 4.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceeff")
        "name" : "Paul"
        "grade" : 3.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef00")
        "name" : "Ringo"
        "grade" : 1.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef01")
        "name" : "Johnny"
        "grade" : 2.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef02")
        "name" : "Joshua"
        "grade" : 1.4
    }
      
]


No comments:

Post a Comment