集合中的Mongoose sum运算

时间:2014-12-31 11:35:53

标签: node.js mongodb mongoose

我有一个名为votes的集合:

    {
        "_id" : ObjectId("54a3cb59b2b8ded51693074d"),
        "Pseudo" : "Cacaboy",
        "Type" : "down",
        "postvote" : ObjectId("54a2f05bedbe1109145b06b6"),
        "CreatedDate" : ISODate("2014-12-31T10:02:34.209Z"),
        "__v" : 0
    }

    {
        "_id" : ObjectId("54a3d776ecbf63c61a91d396"),
        "Pseudo" : "CosmicJB",
        "Type" : "up",
        "postvote" : ObjectId("54a2f05bedbe1109145b06b6"),
        "CreatedDate" : ISODate("2014-12-31T11:01:10.715Z"),
        "__v" : 0
    }

    {
        "_id" : ObjectId("54a3dca5b2b8ded51693074e"),
        "Pseudo" : "hateman",
        "Type" : "down",
        "postvote" : ObjectId("54a2f05bedbe1109145b06b6"),
        "CreatedDate" : ISODate("2014-12-31T10:02:34.209Z"),
        "__v" : 0
    }

实施聚合管道:

Vote.aggregate({$match: {postvote: pvote}}, 
               {$group: {_id: '$Type', 
                         n: { $sum: 1 }
                        }},
               function(err, cb){
                  console.log(cb);
             });

获得o / p:

[ { _id: 'up', n: 1 }, { _id: 'down', n: 2 } ]

所需结果,适用于postvote

  • 如果updown投票,则两者都存在result:up-down
  • 如果只有down票,则result: -down
  • 如果只有up票,则result:up

是否可以使用聚合?

1 个答案:

答案 0 :(得分:0)

您需要修改聚合管道以执行以下操作:

  • Match包含所需postvote个ID的记录。
  • 对于每条记录,为weight - Type的记录投射一个名为up的额外字段, 对于其他1,权重为-1
  • Group基于postvote字段,projectweight字段的总和 postvote result。{/ li>

代码:

Vote.aggregate(
{$match:{"postvote":pvote}},
{$project:{"postvote":1,"weight":{$cond:[{$eq:["$Type","up"]},1,-1]}}},
{$group:{"_id":"$postvote","result":{$sum:"$weight"}}},
function(err,data){
 // handle response.
}
)

样本o / p:

{ "_id" : ObjectId("54a2f05bedbe1109145b06b6"), "result" : -1 }