Reputation: 2459
I am trying to count database records in mongoDB (using mongoose) where records have a status of pending and approved as well as rejected. So, I am basically trying to get a result where I can show a count of each and display it in my view ie:
Pending: 35 Approved: 97 Rejected: 12
I have this but it only counts 'pending'. Is there a way to count all 3 in one query or do I need to run 3 separate queries and get a result for each of them?
Product.countDocuments({status: 'pending', userId: req.session.user._id})
.then(pending => {
if (!pending) {
return next();
}
req.pending = pending;
next();
})
.catch(err => {
console.log(err);
});
EDIT: I have managed to do it like this to a certain extent, well in console I am getting a count of all of the results back but just need to figure out how to get each one into it's own variable.
Product.aggregate([
{ $group: { _id: { status: "$status"}, totalStatus: {$sum: 1} } }
])
.then(function (res) {
console.log(res);
next();
});
Upvotes: 0
Views: 3773
Reputation: 101
For finding multiple count in single query,Please use mongodb aggregation framework it manipulate data in multiple stages, your question is already answered, please visit below link.I update the query for you. Multiple Counts with single query in mongodb
Product.aggregate([
{ "$facet": {
"Pending": [
{ "$match" : { "status": { "$exists": true, "$in":["pending"] }}},
{ "$count": "Pending" },
],
"Approved": [
{ "$match" : {"status": { "$exists": true, "$in": ["approved"] }}},
{ "$count": "Approved" }
],
"Rejected": [
{ "$match" : {"status": { "$exists": true, "$in": ["rejected"] }}},
{ "$count": "Rejected" }
]
}},
{ "$project": {
"Pending": { "$arrayElemAt": ["$Pending.Pending", 0] },
"Approved": { "$arrayElemAt": ["$Approved.Approved", 0] },
"Rejected": { "$arrayElemAt": ["$Rejected.Rejected", 0] }
}}
])
Upvotes: 4