Mongoose SUM + $ cond +数组字段

时间:2016-08-25 10:30:56

标签: node.js mongoose aggregate-functions

"payments": [
          {
            "_id": "57bea755acfbfc4e37c3dfdf",
            "user": "57b1c3d2d591a46848c25f45",
            "transferred_amount": 10,
            "transaction_type": "refund",
            "reason": "#1968 shop box refunded",
            "__v": 0
          },
          {
            "_id": "57beb883acfbfc4e37c3dfe0",
            "user": "57b1c3d2d591a46848c25f45",
            "transferred_amount": 10,
            "transaction_type": "payout",
            "reason": "#1968 shop box refunded",
            "__v": 0
          }
        ]

这是我的数据库数据。

Model.aggragate().project({
            paid_out_amount: {
            $sum: {
                $cond: [{
                    $eq: ['$payments.transaction_type', 'payout']
                }, 0, '$payments.transferred_amount']
            }
        }
})

这是我获取这些数据的节点代码。我正在尝试单独支付金额并将其存储到一个字段中。这里$ cond总是返回零。任何人都可以帮助我。

1 个答案:

答案 0 :(得分:0)

您可以尝试使用$unwind运算符。

像:

Model.aggregate([
{ $unwind: "$payments" },
{
    $group:
         {
           _id: null,
           paid_out_amount: { $sum: {$cond: [ { $eq: [ "$payments.transaction_type", 'payout' ] }, '$payments.transferred_amount', 0 ] } }
         }
}
]);

我假设您要添加transferred_amount payout类型的所有_id:null并返回总和,这就是使用php -f /path/to/file.php param=something > output.html的原因。如果需要,可以通过

添加groupName for group