Arithmetic Operator $multiply in mongo

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

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

Output: 

[
 

      { 
        "_id" : ObjectId("6024b764abea6cc5c99ceefd")
        "name" : "George"
        "grade" : 5.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceefe")
        "name" : "John"
        "grade" : 8.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99ceeff")
        "name" : "Paul"
        "grade" : 6.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef00")
        "name" : "Ringo"
        "grade" : 5.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef01")
        "name" : "Johnny"
        "grade" : 4.0
    }
    { 
        "_id" : ObjectId("6024b764abea6cc5c99cef02")
        "name" : "Joshua"
        "grade" : 7.0
    }
       
]


No comments:

Post a Comment