lookup() method is used between 2 or more collections for join in MongoDB. lookup() method used in the aggregate() method.
Suppose you have 2 collections departments and employees
departments collections
[
{ _id: 1, name: "Engineer", status: 1 },
{ _id: 2, name: "Manager", status: 1 },
{ _id: 3, name: "Peon", status: 1 }
]
employees collections
[
{ _id: 1, name: "John", department_id: 1 }
]
Now, get the employee’s details with the department name.
create the collections_join.js file
var MongoClient = require('mongodb').MongoClient;
let url="mongodb://localhost:27017/";
var options = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
MongoClient.connect(url,options, function (err, connection_obj) {
try{
if (err) throw err;
var dbo = connection_obj.db("users_management");
dbo.collection("employees").aggregate([
{ $lookup:
{
from: 'departments',
localField: 'department_id',
foreignField: '_id',
as: 'departments_details'
}
}
]).toArray(function(err, res) {
if (err) throw err;
console.log("documents show successfully");
console.log(JSON.stringify(res));
connection_obj.close();
});
}catch(err){
console.log("connection fails");
}
Now, run the collections_join.js file.
node collections_join.js
Output:-
documents show successfully
result: [{“_id”:1,”name”:”John”,”department_id”:1,”departments_details”:[{“_id”:1,”name”:”Engineer”,”status”:1}]}]
result: [{“_id”:1,”name”:”John”,”department_id”:1,”departments_details”:[{“_id”:1,”name”:”Engineer”,”status”:1}]}]