Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

157
Views
MongoDB $lookup function replace whole document

I'm currently running a query that looks like this:

courses = await Enrollment.aggregate([
        {
            $match: {
                userId: userId
            }
        },
        {
            $lookup: {
                from: 'courses',
                localField: 'course',
                foreignField: '_id',
                as: 'course'
            }
        },
        { 
            $unwind: '$course'
        },
        {
            $project: {
                course: {
                    courseCode: true,
                    name: true,
                    officialCode: true,
                }
            }
        }
    ]);

This produces results that look like this

[{
    "_id": "61e0652ba5c2fe5bdcdbdc23",
    "course": {
        "courseCode": "code2",
        "name": "Terst class 2",
        "officialCode": "test 202"
    }
}]

I'm wondering if there is a way for me to bring courseCode, name and officialCode to the "highest level" of the document?

Thank you in advance.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can do it with $replaceRoot aggregation pipeline. Add this as the last step:

{
  "$replaceRoot": {
    "newRoot": "$course"
  }
}

Working example

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!