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

94
Visualizações
Mongodb sort Aggregation in same order ids was passed on filter

I would like to know if its possible to keep the current order of the result the same as it is passed in on the filtering.

So lets say we have an array of IDS:

var arrayValues = [1,3,2]

I would like to aggregate the values but keep the result same order as im passing in the above array.

 var result = Item.aggregate([{ $match: { _id: { $in: arrayValues } }}])

I would want the result in same order as the array values passed in as _id value.

Example Result :

result = [{ _id: 1 },{ _id: 3 },{ _id: 2 }]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use indexOfArray for this:

db.collection.aggregate([
  {$match: {_id: {$in: arrayValues}}},
  {$set: {index: {$indexOfArray: [arrayValues, "$_id"]}}},
  {$sort: {index: 1}},
  {$unset: "index"}
])

See how it works on the playground 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