Search code examples
mongodbspring-dataaggregation-frameworkspring-mongo

MongoDB counts multiple fields


Here is the input collection :

{"itemName" : "A1", "voteType" : "up"}
{"itemName" : "A1", "voteType" : "up"}
{"itemName" : "A1", "voteType" : "down"}
{"itemName" : "A2", "voteType" : "up"}
{"itemName" : "A2", "voteType" : "down"}
{"itemName" : "A2", "voteType" : "down"}
{"itemName" : "A2", "voteType" : "down"}
and so on...

Does anyone know how to get the following documents with Aggregation?

Also, how can we use Spring Data to implement this?

{ "id" : "A1", "CountUp" : 2, "CountDown" : 1}
{ "id" : "A2", "CountUp" : 1, "CountDown" : 3}

Solution

  • this should work. The $cond operator can be used to populate the CountUp and CountDown fields. After that its just grouping the data

         {
             $project:
               {
                 itemName: 1,
                 countUp:
                   {
                     $cond: [ { $eq: [ "$voteType", "up" ] }, 1, 0 ]
                   },
                   countdown:
                   {
                     $cond: [ { $eq: [ "$voteType", "down" ] }, 1, 0 ]
                   }
               }
          },
    
         { $group : { _id : "$itemName", countUp: { $sum: "$countUp" }, countDown: { $sum: "$countdown" } }}