问题
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