You can use $facet aggregation operator to output a single document based on multiple aggregation pipeline results. In the example below, the output structure is determined by facets: countByClass for the total number of students per class and passFailCount for the total number of students under pass and fail branches, which is based on whether their score is greater than or equal to 70 or not, respectively.
// test data
db.getCollection("students").insertMany([
{ name: "Student1", class: "A", score: 92 },
{ name: "Student2", class: "A", score: 74 },
{ name: "Student3", class: "B", score: 85 },
{ name: "Student4", class: "B", score: 61 },
{ name: "Student5", class: "A", score: 48 },
]);
db.getCollection("students").aggregate([
{
$facet: {
countByClass: [{ $group: { _id: "$class", count: { $sum: 1 } } }, { $sort: { _id: 1 } }],
passFailCount: [
{
$group: {
_id: { $cond: [{ $gte: ["$score", 70] }, "pass", "fail"] },
count: { $sum: 1 },
},
},
],
},
},
]);
Output:
[
{
"countByClass": [
{
"_id": "A",
"count": 3
},
{
"_id": "B",
"count": 2
}
],
"passFailCount": [
{
"_id": "fail",
"count": 2
},
{
"_id": "pass",
"count": 3
}
]
}
]