Mongodb多级聚合

时间:2019-09-06 06:09:02

标签: mongodb

mongo中的数据

[{  
    "_id": "5d71d1432f7c8151c58c4481",
    "payment": {
        "transactions": [
            {
                "_id": "5d71d1ff2f7c8151c58c44cf",
                "method": "paytm",
                "amount": 100,
                "paymentOn": "2019-09-06T03:26:44.959Z"
            }, 
            {
                "_id": "5d71d1ff2f7c8151c58c44ce",
                "method": "cash",
                "amount": 650,
                "paymentOn": "2019-09-06T03:26:55.531Z"
            }
        ],
        "status": "partial"
    },
    "customer": "5d66c434c24f2b1fb6772014",
    "order": {
        "orderNumber": "WP-ORD-06092019-001",
        "total": 770,
        "balance": 20
    }
},
{
    "_id": "5d71d1432f7c8151c58c4481",
    "payment": {
        "transactions": [
            {
                "_id": "5d71d1ff2f7c8151c58c44cf",
                "method": "paytm",
                "amount": 100,
                "paymentOn": "2019-09-06T03:26:44.959Z"
            }
        ],
        "status": "partial"
    },
    "customer": "5d66c434c24f2b1fb6772014",
    "order": {
        "orderNumber": "WP-ORD-06092019-001",
        "total": 200,
        "balance": 100
    }
}]

我想按方法汇总付款。 因此结果如下所示:

Output:
Paytm: 200
Cash : 650
Unpaid(Balance): 120

我尝试过:

[
  {
    '$unwind': {
      'path': '$payment.transactions', 
      'preserveNullAndEmptyArrays': true
    }
  }, {
    '$project': {
      'amount': '$payment.transactions.amount', 
      'method': '$payment.transactions.method'
    }
  }, {
    '$group': {
      '_id': '$method', 
      'amount': {
        '$sum': '$amount'
      }
    }
  }
] 

但是如何也包括余额计算

2 个答案:

答案 0 :(得分:1)

使用上面的数据集,使用聚合管道进行计算,并将聚合用作:

db.collection.aggregate([
  {
    $facet: {
      paidAmounts: [
        { '$unwind': { 'path': '$payment.transactions', 'preserveNullAndEmptyArrays': true } },
        {
          $group: {
            _id: "$payment.transactions.method",
            amount: {
              $sum: "$payment.transactions.amount"
            }
          }
        }
      ],
      leftAmounts: [
        {
          $group: {
            _id: null,
            balance: {
              $sum: "$order.balance"
            }
          }
        }
      ]
    }
  }
])

给出输出:  这里leftAmounts剩余余额,并且payAmounts根据付款类型对付款数据进行分组

[
  {
    "leftAmounts": [
      {
        "_id": null,
        "balance": 120
      }
    ],
    "paidAmounts": [
      {
        "_id": "cash",
        "amount": 650
      },
      {
        "_id": "paytm",
        "amount": 200
      }
    ]
  }
]

答案 1 :(得分:1)

工作解决方案:https://mongoplayground.net/p/7IWELKKMsWe

 router.post("/request/partial", async (req, res) => {
      const partial = new PartialRequest({
        startingDate: req.body.startingDate,
        requestID: req.body.requestID,
        whoCreated: req.body.whoCreated,
        isNewRequest: true,
        specialRequest: req.body.specialRequest,
        contactInformation: req.body.contactInformation,
        requestInformation: req.body.requestInformation,
        orderInformation: req.body.orderInformation,
        jobSiteInformation: req.body.jobSiteInformation,
 installations : req.body.installations;
      });
    await partial.save().then(result => {
        return res.status(200).json({
          message: 'Handling POST request to /partial',
          result: result
        });
      });
      await Request.findOneAndRemove({
        requestID: req.body.requestID
      }).then(data => {
        return res.status(200).json(data);
      }).catch(error => {
        return res.status(500).json({
          error: error
        })
      })
    })