MongoDB计算多个字段

时间:2015-02-04 11:33:36

标签: mongodb spring-data aggregation-framework spring-mongo

这是输入集合:

{"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...

有没有人知道如何使用聚合获取以下文档?

另外,我们如何使用Spring Data来实现它?

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

1 个答案:

答案 0 :(得分:2)

这应该有效。 $cond运算符可用于填充CountUpCountDown字段。之后它只是对数据进行分组

     {
         $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" } }}