MongoDB Inner join using aggregate and lookup

Below is the sample query with explanations :-

Collection1Name.aggregate([
{ “$match”: { “Id”: new mongoose.Types.ObjectId(req.params.id) } },
{ $lookup:
{
from: ‘Collection2Name’,
localField: ‘localfieldName’,
foreignField: ‘foreignfieldName’,
as: ‘info’
}
}, {
$unwind: “$info”,
},
]).exec((err, result)=>{
if (err) {
console.log(“error” ,err)
}
if (result) {
console.log(‘zx zxcz’,result);

}
});

$match — This will match/filter your data base on id or some values

Collection1Name — Please specify collection1name. So for e.g If you have imported collection like this const TableName1= require(‘../models/collection’); then you can mention TableName1

Collection2Name — Please specify collection2name . So for e.g If you have imported collection like this const TableName= require(‘../models/collection’); then you can mention tablenames

localField — Please specify local field name from Collection1Name

foreignField — Please specify foreign filed name from Collection2Name

$unwind — To deconstruct it into a sub-document

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store