MongoDB $lookup function replace whole document

528 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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

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

Working example