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

196
Views
MongoDB $lookup and $group returns empty Array

I am trying to use the following aggregation:

[
    {$unwind: '$names'},
    {$sort: {'names.changed_at': -1}},
    {$group: {_id: '$_id', names: {$push: {value: '$names.value', changed_at: '$names.changed_at'}}}},
    {$limit: 3},
    {
        $lookup: {
            from: 'users',
            localField: 'id',
            foreignField: 'id',
            as: 'user',
        },
    },
    {$unwind: '$user'},
    {
        $project: {
            _id: 0,
            old_name: {$first: '$names'},
            user: {avatar_url: 1, current_tag: 1},
        },
    }
]

With $lookup and $group it returns []. When I remove either $lookup or $group it works and gives the expected result.

How do I fix this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You're trying to use the id field for the $lookup but after this $group stage:

{ $group: { _id: '$_id', names: { $push: { value: '$names.value', changed_at: '$names.changed_at' } } } },

The document structure is:

{
  _id: ObjectId,
  names: { value: string, changed_at: Date }[]
}

As you can see, there is no id field.

If this is a typo just change id to _id. if this is not a typo then you need to "save" the id field in the $group stage, like so:

{
    $group: {
        _id: '$_id',
        names: {$push: {value: '$names.value', changed_at: '$names.changed_at'}},
        id: {$first: "$id"}
    }
}
about 4 years ago · Juan Pablo Isaza 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!