Yesterday, I used $addToSet to attach a unique set of values in the output document per group. This time, I want the array sorted. In the example below, the first pipeline stage creates the unique set of scores per class in uniqueScores. The next stage pereforms sorting with $set, which is an aggregation operator that modifies the result/grouped documents from the previous stage. Here, uniqueScores is reassigned with the output of $sortArray, an operator that accepts the uniqueScores values as input and sorts it in ascending order with sortBy.
// test data
db.getCollection("students").insertMany([
{ name: "Student1", class: "A", score: 92 },
{ name: "Student2", class: "A", score: 74 },
{ name: "Student3", class: "A", score: 74 },
{ name: "Student4", class: "B", score: 85 },
{ name: "Student5", class: "B", score: 61 },
{ name: "Student6", class: "A", score: 48 },
{ name: "Student7", class: "B", score: 85 },
]);
db.getCollection("students").aggregate([
{
$facet: {
scoresBySection: [
{
$group: {
_id: "$class",
uniqueScores: { $addToSet: "$score" },
},
},
{
$set: {
uniqueScores: { $sortArray: { input: "$uniqueScores", sortBy: 1 } },
},
},
{ $sort: { _id: 1 } },
],
},
},
]);
Output:
[
{
"scoresBySection": [
{
"_id": "A",
"uniqueScores": [48, 74, 92]
},
{
"_id": "B",
"uniqueScores": [61, 85]
}
]
}
]