我有一个名为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
:
up
和down
投票,则两者都存在result:up-down
。down
票,则result: -down
。up
票,则result:up
。是否可以使用聚合?
答案 0 :(得分:0)
您需要修改聚合管道以执行以下操作:
Match
包含所需postvote
个ID的记录。weight
- Type
的记录投射一个名为up
的额外字段,
对于其他1
,权重为-1
。Group
基于postvote
字段,project
为weight
字段的总和
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 }