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

119
Visualizações
Mongodb find multiple and retrive one record for matching id

I'm trying to find many records in the same query, the records are of this type

{
    "key": 2,
    time: 3
  },
  {
    "key": 2,
    time: 5
  },
  {
    "key": 3,
    time: 4
  }

I'd like to retrive for example the records with key inside [2,3] and with the relative maximum amount of time, so in this case recrods with { "key": 2, time: 5 } and { "key": 3, time: 4 } should be returned.

So far i got only how to retrive the records with key inside in a proveded array but i'm not understanding how to get for each key in the array the record with the latest time, i'd like to not use the where operator.

Here is a playground with the provided scenario https://mongoplayground.net/p/5sWnn8_HnqK

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You can use aggregate function to find max element for each key. Example: https://mongoplayground.net/p/P9JSuvTHdZa

    db.collection.aggregate([
  {
    $match: {
      key: {
        $in: [
          2,
          3
        ]
      }
    }
  },
  {
    $group: {
      _id: "$key",
      time: {
        $max: "$time"
      }
    }
  }
])

Edited: as in comment suggested

over 4 years ago · Santiago Trujillo Relatório

0

The easiest way to achieve this is by matching the documents, sorting them descendingly and then choose the "first" document for each key, like so:

db.collection.aggregate([
  {
    $match: {
      key: {
        $in: [
          1,
          2,
          3
        ]
      }
    }
  },
  {
    $sort: {
      time: -1
    }
  },
  {
    $group: {
      _id: "$key",
      first: {
        $first: "$$ROOT"
      }
    }
  }
])
over 4 years ago · Santiago Trujillo 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