How to conditionally aggregate result

I have a collection based on which I need to calculate the score, which is as simple as this.

Calculate points for all students in my collection If a student belongs to class "A" or "B" he gets 5 points, if he belongs to class "C" or "D" he gets 4

Student:

{
    name:"Aster",
    classes:['A','B']
}

      

Aggregation does not allow $ in statement on $ cond as I can proceed

Ps: Sorry. Brevity sent on the go

+3


source to share


1 answer


Not sure if this can completely solve your problem, but you can use $setIsSubset

in Mongo 2.6:

db.collection.aggregate([
   { $project: { name: 1 , 
                 grade: { $cond: [{$setIsSubset: ["$classes", ["A","B"]]}, 5, 4]}     
               } 
   }])

      



In case it classes

can be either a string or an array:

db.collection.aggregate([
   { $project: { name: 1 , 
                 grade: {$cond: [{$or: [{$eq: ["$classes", "A"]}, 
                                        {$eq: ["$classes", "B"]}, 
                                        {$setIsSubset: ["$classes", ["A","B"]]}]}, 
                                 5, 4]}     
               } 
   }])

      

+4


source







All Articles