Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda