skip to content
Alvin Lucillo

Preserve raw/unsorted arrays

/ 2 min read

In the previous day’s entry, I used $addToSet to set an unsorted array of scores to uniqueScores and sort it with $sortArray.

Today, to see both the raw and sorted versions, I used $project. scoresBySection sub-pipeline has a stage that saves unique scores to uniqueScoresRaw and the second stage that transforms it with $project. The projected document has the _id (the class), uniqueScoresRaw (from earlier stage), and uniqueScoresSorted (the sorted uniqueScoresRaw)

// 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",
						uniqueScoresRaw: { $addToSet: "$score" },
					},
				},
				{
					$project: {
						_id: 1,
						uniqueScoresRaw: 1,
						uniqueScoresSorted: { $sortArray: { input: "$uniqueScoresRaw", sortBy: 1 } },
					},
				},
				{ $sort: { _id: 1 } },
			],
		},
	},
]);

Output:

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