skip to content
Alvin Lucillo

Aggregation with unwind

/ 1 min read

The $unwind aggregation flattens the array property of a document so that there will be a document for each array element.

Get a sample document with array property diet

// db.birds.aggregate([{$match: {common_name: "Northern Cardinal"}}])
[
	{
		_id: ObjectId("6286809e2f3fa87b7d86dccd"),
		common_name: "Northern Cardinal",
		scientific_name: "Cardinalis cardinalis",
		wingspan_cm: 25.32,
		habitat: "woodlands",
		diet: ["grain", "seeds", "fruit"],
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
];

Flattening the arrays with $unwind so we got 3 documents, each with just one diet element

// db.birds.aggregate([{$match: {common_name: "Northern Cardinal"}}, {$unwind: "$diet"}])
[
	{
		_id: ObjectId("6286809e2f3fa87b7d86dccd"),
		common_name: "Northern Cardinal",
		scientific_name: "Cardinalis cardinalis",
		wingspan_cm: 25.32,
		habitat: "woodlands",
		diet: "grain",
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
	{
		_id: ObjectId("6286809e2f3fa87b7d86dccd"),
		common_name: "Northern Cardinal",
		scientific_name: "Cardinalis cardinalis",
		wingspan_cm: 25.32,
		habitat: "woodlands",
		diet: "seeds",
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
	{
		_id: ObjectId("6286809e2f3fa87b7d86dccd"),
		common_name: "Northern Cardinal",
		scientific_name: "Cardinalis cardinalis",
		wingspan_cm: 25.32,
		habitat: "woodlands",
		diet: "fruit",
		last_seen: ISODate("2022-05-19T20:20:44.083Z"),
	},
];