Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

251
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda