In this article, we will learn how to join multiple collections with $lookup.
$lookup function allows us to join multiple collections in the same database. the $lookup function (joined collection) will return the sub-array of matched data.
syntax:
$lookup: { from: collection to join, localField: field from the execute query document, foreignField: field from the join collection document(match with localField), as:name of the output array }
from: specifies the collection to perform the join.
localField: specifies the field from the document whose field match to the other collection document
foreignField : specifies the field from the other document
as: specifies the name of the new array to add the result
–first, we need to create two collections:
- schema:
//for employee collection var employeeSchema = new mongoose.Schema({ name: { type: String, }, email: { type: String, } }); //for employeedata collection var employeeDataSchema = new mongoose.Schema({ empid: { type: mongoose.Schema.ObjectId, }, address: { type: String, }, phone: { type: Number, } }); const empSchema = mongoose.model('employee', employeeSchema); const empDataSchema = mongoose.model('employeedata', employeeDataSchema);
- insert data in employee collection:
//insert data in employee collection exports.addEmp = async (req, res) => { let data = await new empSchema(req.body).save() res.status(200).send({ isSuccess: true, data:data }); }
output:
- insert data in employeedata collection
exports.add = async (req, res) => { let result = new empDataSchema(req.body).save() res.status(200).send({ isSuccess: true, data:result }); }
output:
–join employee and employeedata collection using $lookup
exports.empData = async (req, res) => { const data = await empSchema.aggregate([ { $lookup: { from: "employeedatas", localField: "_id", foreignField: "empid", as: "emp" } } ]); res.status(200).send({ isSuccess: true, data: data }); }
output: