Since a group collapses multiple documents into a single document, you must need an accumulator like $first to select the document. This accumulator picks the first document from the group. In the example below, the name is selected based on the first document in the group. $name points to the name property of the selected document.
// 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 },
firstStudentName: { $first: "$name" },
},
},
{ $sort: { _id: 1 } },
],
},
},
]);
Output:
[
{
"countByClass": [
{
"_id": "A",
"count": 3,
"firstStudentName": "Student1"
},
{
"_id": "B",
"count": 2,
"firstStudentName": "Student3"
}
]
}
]