MongoDB Simple Joins
JS
S
JavaScriptSimple joins with MongoDB
1const simpleJoin1 = await CarModel.aggregate()
2 .lookup({
3 from: 'patches',
4 localField: 'homePatch',
5 foreignField: '_id',
6 as: 'homePatch',
7 })
8 .unwind('homePatch')
9 .match({
10 'homePatch.code': 'PT',
11 'homePatch.name': 'Portugal',
12 });
13
14const simpleJoin2 = await CarModel.aggregate()
15 .lookup({
16 from: 'patches',
17 let: { carHomePatch: '$homePatch' },
18 pipeline: [{ $match: { $expr: { $and: [{ $eq: ['$code', 'PT'] }, { $eq: ['$name', 'Portugal'] }, { $eq: ['$$carHomePatch', '$_id'] }] } } }],
19 as: 'homePatch',
20 })
21 .unwind('homePatch');Created on 3/16/2021