skip to content
Alvin Lucillo

Aggregation sort stage

/ 1 min read

Aggregation $sort stage allows us to sort collections in ascending (1) or descending (-1) order before other stages transform the data.

Returns all documents

//  db.birds.find({})
[
	{
		_id: ObjectId("626845c4613e55b82d7065d5"),
		common_name: "Sanderling",
		scientific_name: "Calidris alba",
		wingspan_cm: 43.18,
		habitat: "wetlands",
		diet: ["crustaceans", "oceanic invertebrates"],
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
	{
		_id: ObjectId("62684641613e55b82d7065d6"),
		common_name: "Rock Pigeon",
		scientific_name: "Columba livia",
		wingspan_cm: 71.12,
		habitat: ["urban parks", "farmland"],
		diet: ["grass", "grain", "fruit", "weeds", "vegetables"],
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
	{
		_id: ObjectId("62684c8c613e55b82d7065d8"),
		common_name: "Purple Martin",
		scientific_name: "Progne Subis",
		wingspan_cm: 45.72,
		habitat: "field",
		diet: ["insects"],
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
];

Performs aggregation by sorting documents by common_name in ascending order

//  db.birds.aggregate([{$sort: {common_name: 1}}])
[
	{
		_id: ObjectId("62684c8c613e55b82d7065d8"),
		common_name: "Purple Martin",
		scientific_name: "Progne Subis",
		wingspan_cm: 45.72,
		habitat: "field",
		diet: ["insects"],
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
	{
		_id: ObjectId("62684641613e55b82d7065d6"),
		common_name: "Rock Pigeon",
		scientific_name: "Columba livia",
		wingspan_cm: 71.12,
		habitat: ["urban parks", "farmland"],
		diet: ["grass", "grain", "fruit", "weeds", "vegetables"],
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
	{
		_id: ObjectId("626845c4613e55b82d7065d5"),
		common_name: "Sanderling",
		scientific_name: "Calidris alba",
		wingspan_cm: 43.18,
		habitat: "wetlands",
		diet: ["crustaceans", "oceanic invertebrates"],
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
];