How can I sum total of cancellation per month grouped by years in MongoDB?

喜欢而已 提交于 2020-03-25 17:57:27

问题


I am optimizing an end-point for my API, and I would like to get the total of cancellations of Service A, B and others from Jan to Dec grouped by year.

This is the output that I would love to get from my end-point:

  [
    {
        "_id:"{
            "name": "Product A"
        }, 
        "2017": {
            "January": 2500,
            "February": 3000,
            "March": 1500,
            "April": 4500,
            "May": 3250,
            "June": 9080, 
            "July": 1120,
            "August": 890,
            "September": 5789,
            "Octuber": 7899,
            "November": 3459,
            "Decemeber": 2300
    },
    {
        "_id": {
            "name": "Product B",
        },
        "2018": {
            "January": 789,
            "February": 2304,
            "March": 1000,
            "April": 4500,
            "May": 2250,
            "June": 9080, 
            "July": 1120,
            "August": 890,
            "September": 4789,
            "Octuber": 5000,
            "November": 3500,
            "Decemeber": 2300       
    }
 ]

The values to be used are:

  • "type_of_service"
  • "management_fee"

This is how the JSON looks like:

{

    "type_of_service": "Service A",
    "management_fee": 2000,
    "sales_date": "2018-07-29",
    "cancellation_date":"2019-05-05",
    "country": "USA",
    "state": "Texas",

}

This is my code so far:

 router.get('/total_cancellation_byYear', auth, async (req, res) => {

  try {

    const model_CancellationKPI = await CancellationKPI.aggregate(
      [
        {
          $group:
            {
              _id: { year: { $year: "$cancellation_date" } },
              totalAmount: { $sum: "$management_fee" },
              count: { $sum: 1 }
            }
        }
      ]
   )

   res.json(model_CancellationKPI);

  } catch (err) {
    console.error(err.message); 
    res.status(500).send('Server Error')
  }

});

And, this is the output:

[
    {
        "_id": {
            "year": 2017
        },
        "totalAmount": 16197,
        "count": 16
    },
    {
        "_id": {
            "year": 2019
        },
        "totalAmount": 33681,
        "count": 32
    },
    {
        "_id": {
            "year": 2018
        },
        "totalAmount": 24655,
        "count": 45
    }
]

I would really appreciate your support on this.

来源:https://stackoverflow.com/questions/57740563/how-can-i-sum-total-of-cancellation-per-month-grouped-by-years-in-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!