skip to content
Alvin Lucillo

Showing unique values as array

/ 1 min read

Use $addToSet accumulator to return unique values of a specific property in a group pipeline stage. In the example below, the goal is to return the class name and their unique scores.

// 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" },
					},
				},
				{ $sort: { _id: 1 } },
			],
		},
	},
]);

Output:

[
	{
		"scoresBySection": [
			{
				"_id": "A",
				"uniqueScores": [92, 74, 48]
			},
			{
				"_id": "B",
				"uniqueScores": [85, 61]
			}
		]
	}
]