Write a query to use the $subtract 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 Subtract 2 in grade when grade >5.
db.getCollection("people").aggregate([{$match:{ "school" : "MathHighSchool"}},{$project:{"name":1,"grade":{$cond:{if:{$gt:["$grade",5]},then:{$subtract:["$grade",2]},else:"$grade"}}}}]);
Output:
[{"_id" : ObjectId("6024b764abea6cc5c99ceefd"),"name" : "George","grade" : 5.0}{"_id" : ObjectId("6024b764abea6cc5c99ceefe"),"name" : "John","grade" : 4.0}{"_id" : ObjectId("6024b764abea6cc5c99ceeff"),"name" : "Paul","grade" : 3.0}{"_id" : ObjectId("6024b764abea6cc5c99cef00"),"name" : "Ringo","grade" : 5.0}{"_id" : ObjectId("6024b764abea6cc5c99cef01"),"name" : "Johnny","grade" : 2.0}{"_id" : ObjectId("6024b764abea6cc5c99cef02"),"name" : "Joshua","grade" : 5.0}]
No comments:
Post a Comment