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

259
Vistas
How to get last defined value in an aggregration in MongoDB?

I have a collection in which the documents sometimes contain a status field and sometimes don't. There is always a data field. I'm trying to form a query to get the latest value for both, but when using the $last operator, I get the values from the latest document and results in status sometimes being null. How can I get it to retrieve the latest defined status value, while still keeping the data value from the latest document?

Current aggregration:

  const project = await collection.aggregate([
    {
      $match: {
        projectId: id
      }
    },
    {
      $group: {
        _id: '$projectId',
        status: {
          $last: '$status'
        },
        data: {
          $last: '$data'
        }
      }
    }
  ]).toArray();
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use $facet and perform multiple query in the parallel on the same set of documents.

db.collection.aggregate([
  {
    $facet: {
      last_status: [
        {
          "$match": {
            status: {
              $ne: null
            }
          }
        },
        {
          "$sort": {
            _id: -1
          }
        },
        {
          "$limit": 1
        }
      ],
      last_data: [
        {
          "$match": {
            data: {
              $ne: null
            }
          }
        },
        {
          "$sort": {
            _id: -1
          }
        },
        {
          "$limit": 1
        }
      ]
    }
  },
  {
    "$project": {
      other_fields: {
        $first: "$last_data"
      },
      status: {
        $first: "$last_status.status"
      }
    }
  }
])

Working example

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