I am currently working on a query that involves using find and aggregate to retrieve data from the Schedule model. I need to calculate the total sum of services and the total value of services, but with a condition where the status is equal to 2. Is it possible to achieve this?
Here is my current query:
Schedule.find(findTerm)
.skip(req.body.page * req.body.limit)
.limit(Number(req.body.limit))
.select(
"service.name value scheduleStart scheduleEnd comissionValue status paymentMethod"
)
.exec((err, response) => {
if (err) res.status(500).send(err);
Schedule.find(findTerm)
.count()
.exec((error, count) => {
if (error)
res.status(500).send({
error,
code: 0,
message: "Error."
});
Schedule.aggregate([{
$match: {
store: req.body.store,
}
},
{
$group: {
_id: {
id: "$store"
},
totalValue: {
$sum: "$value"
},
totalServices: {
$sum: {
$cond: [ {
$eq: [ "$status", 2 ]
}]
}
},
count: {
$sum: 1
}
}
}...
Result of my query:
...{
"service": {
"name": "CABELO + BARBA"
},
"comissionValue": 0,
"paymentMethod": 0,
"_id": "5bfec336c6f00d2e88f8d765",
"scheduleStart": "2018-11-28 14:35",
"scheduleEnd": "2018-11-28 15:45",
"status": 2,
"value": 75
},
{
"service": {
"name": "Barba"
},
"comissionValue": 0,
"paymentMethod": 0,
"_id": "5bfec3ffc6f00d2e88f8d766",
"scheduleStart": "2018-11-28 18:30",
"scheduleEnd": "2018-11-28 18:50",
"status": 2,
"value": 20
}
],
"count": 4299,
"group": [
{
"_id": {
"id": "5b16cceb56a44e2f6cd0324b"
},
"totalValue": 777780048281, //correct value
"totalServices": 945, //incorrect value
"count": 676
}
]
}
I need to only include objects in the totalServices sum where the status is equal to 2 (I attempted to use $cond but it did not work).