0

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}

1 Answer 1

2

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" } }} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.