skip to content
Alvin Lucillo

Aggregation with lookup

/ 1 min read

A $lookup aggregation pipeline performs a left outer join. For example, we have these sample documents below. transfers collection is related to accounts with to_account and from_account.

// db.transfers.find({})
[
	{
		_id: ObjectId("62d6e072cab6d8e1304974b7"),
		transfer_id: "TR492599144",
		to_account: "MDB584129186",
		from_account: "MDB835466518",
		amount: Decimal128("2779"),
	},
][
	// db.accounts.find({})
	{
		_id: ObjectId("62d6e04ecab6d8e13049748b"),
		account_id: "MDB659507055",
		account_holder: "Jacob Thompson",
		account_type: "checking",
		balance: Decimal128("3887.53000000000"),
		transfers_complete: ["TR806791572", "TR437437431", "TR512378671"],
	}
];

The simple $lookup returns transfers with new field from_account_details coming from the accounts collection. This is based on this join: accounts.account_id = transfers.from_acccount

// db.transfers.aggregate([
// ...   {
// ...     $lookup: {
// ...       from: "accounts",
// ...       localField: "from_account",
// ...       foreignField: "account_id",
// ...       as: "from_account_details"
// ...     }
// ...   }
// ... ])
[
	{
		_id: ObjectId("62d6e072cab6d8e1304974b7"),
		transfer_id: "TR492599144",
		to_account: "MDB584129186",
		from_account: "MDB835466518",
		amount: Decimal128("2779"),
		from_account_details: [
			{
				_id: ObjectId("62d6e04ecab6d8e1304974ab"),
				account_id: "MDB835466518",
				account_holder: "Ellinor Moss",
				account_type: "checking",
				balance: Decimal128("3467.69000000000"),
				transfers_complete: [
					"TR492599144",
					"TR958659200",
					"TR369704039",
					"TR465571137",
					"TR884402901",
					"TR221622617",
				],
			},
		],
	},
];