Aggregate Mongo queries accept multiple steps, including SQL-style joins using $lookup
. This will add a new property to the results, with an array of documents from the other collection. You can then use $unwind
to make each result map to a single document from the other collection. Finally, $project
can help you select only the fields you care about.
For example, assuming collectionA
has fields id
, valueA
, and otherId
; and collectionB
, id
and valueB
, you can do this to join the two as if they were SQL tables, selecting both ids and both value*
fields:
db.collectionA.aggregate([
{$lookup: {from: "collectionB", localField: "otherId", foreignField: "id", as: "joinedData"}},
{$unwind: "joinedData"},
{$project: {
id: 1,
valueA: 1,
otherId: "$joinedData.id",
valueB: "$joinedData.valueB",
}},
])
{$lookup: {from: "collectionB", localField: "otherId", foreignField: "id", as: "joinedData"}},
{$unwind: "joinedData"},
{$project: {
id: 1,
valueA: 1,
otherId: "$joinedData.id",
valueB: "$joinedData.valueB",
}},
])