Open In App

Mongoose Aggregate.prototype.lookup() API

Last Updated : 26 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The Mongoose Aggregate prototype.lookup() method of the Mongoose API is used to perform aggregation tasks. It allows us to perform left join the operation between the collection in the same database to filter out the documents based on requirements and conditions. Let us understand lookup() method using an example.

Syntax:

aggregate.lookup( <object> );

Parameters: This method accepts a single parameter as described below:

  • object: It is used to specify various properties like: from, localField, foreignField, for the method execution.

Return Value: This method returns the aggregated result set in the form of an array.

Setting up Node.js Mongoose Module:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this: 

 

Database Structure: The database structure will look like this, the following documents are present in the collection.

  • students collection:

 

  • marks collection:

 

Example 1: In this example, we have established a database connection using mongoose and defined the model over studentSchema and marksSchema. In the end, we call the loopup() method by passing various property values in the object form. We are getting the expected result in the form of an array. To get a better picture we are extracting the first object from the result array.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String },
    age: { type: Number },
    rollNumber: { type: Number },
});
  
const marksSchema = new mongoose.Schema({
    english: Number,
    maths: Number,
    science: Number,
    socialScience: Number,
    hindi: Number,
    rollNumber: Number
})
  
const Student = connectionObject.model('Student', studentSchema);
  
const Mark = connectionObject.model('Mark', marksSchema);
  
Student.aggregate().lookup({
    from: 'marks',
    localField: 'rollNumber', foreignField: 'rollNumber',
    as: 'student_marks'
}).exec((error, result) => {
    if (error) {
        console.log('error - ', error);
  
    } else {
        console.log('result - ', result[0]);
    }
})


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

result - {
    _id: new ObjectId("63a40a1065e8951038a391b1"),
    name: 'Student1',
    age: 20,
    rollNumber: 9,
    __v: 0,
    student_marks: [
        {
            _id: new ObjectId("63a4aadedbfff3b8898083c3"),
            english: 50,
            maths: 60,
            science: 75,
            socialScience: 68,
            hindi: 58,
            rollNumber: 9,
            __v: 0
        }
    ]
}

Example 2: In this example, we have established a database connection using mongoose and defined the model over studentSchema and marksSchema. In the end, we are using the aggregation pipeline and configuring $lookup object. We are getting the expected result in the form of an array. In the end, we are iterating the array using forEach method and displaying the name of the student and the marks of the student.

Filename: app.js

Javascript




// Require mongoose module
const mongoose = require("mongoose");
  
// Set Up the Database connection
  
const connectionObject = mongoose.createConnection(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
});
  
const studentSchema = new mongoose.Schema({
    name: { type: String },
    age: { type: Number },
    rollNumber: { type: Number },
});
  
const marksSchema = new mongoose.Schema({
    english: Number,
    maths: Number,
    science: Number,
    socialScience: Number,
    hindi: Number,
    rollNumber: Number
})
  
const Student = connectionObject.model('Student', studentSchema);
const Mark = connectionObject.model('Mark', marksSchema);
  
(async () => {
    const result = await Student.aggregate([{ $lookup: 
        { from: 'marks', localField: 'rollNumber'
          foreignField: 'rollNumber', as: 'student_marks' } }])
    result.forEach(student => {
        console.log(student.name)
        console.log(student.student_marks);
    })
})();


Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

Student1
[
    {
        _id: new ObjectId("63a4aadedbfff3b8898083c3"),
        english: 50,
        maths: 60,
        science: 75,
        socialScience: 68,
        hindi: 58,
        rollNumber: 9,
        __v: 0
    }
]
Student3
[
    {
        _id: new ObjectId("63a4aadedbfff3b8898083c4"),
        english: 90,
        maths: 60,
        science: 55,
        socialScience: 78,
        hindi: 68,
        rollNumber: 178,
        __v: 0
    }
]
Student4
[
    {
        _id: new ObjectId("63a4aadedbfff3b8898083c5"),
        english: 55,
        maths: 68,
        science: 85,
        socialScience: 87,
        hindi: 85,
        rollNumber: 152,
        __v: 0
    }
]
Student2
[
    {
        _id: new ObjectId("63a4aadedbfff3b8898083c6"),
        english: 75,
        maths: 88,
        science: 45,
        socialScience: 65,
        hindi: 80,
        rollNumber: 176,
        __v: 0
    }
]

Reference: https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-lookup



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads