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

104
Visualizações
Project and then sort in mongoose for array fields

I have a mongoose model for a post on a social-media-like website called PostModel:

{
caption: String,
likes: [] // array to store info about users who liked the video, basically a ref to a different model
comments: [] // array to store comment objects
}

I want to sort all the videos in a find query based on the number of likes, which here would be the length of the "likes" array. If two posts have same number of likes, I want to sort by the number of comments, or otherwise, the length of the "comments" array.

The problem is that it is not working. This is what I tried:

PostModel.find({}, {
  likes: { $size: "$likes" },
  comments: { $size: "$comments" }
}, 
{
  sort: { likes: -1, comments: -1 } // gives "cannot sort with keys that are parallel arrays" error
})

This lead me to believe that the sorting happens before the projection. To confirm, I tried the following query:

PostModel.find({}, {
  _l: { $size: "$likes" },
  _c: { $size: "$comments" }
}, 
{
  sort: { _l: -1, _c: -1 }
})

This query did not give any errors but did not sort the resultant array at all. So, it is confirmed that the projection actually happens after the sorting in mongoose.

How should I sort the resultant array by number of likes and number of comments in this case?

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

0

I tried this aggregation and it works perfectly fine for me with your data:

 PostModel.aggregate([ { '$set': { 'likes': { '$size': '$likes' }, 'comments': { '$size': '$comments' } } }, { '$sort': { 'likes': -1, 'comments': -1 } } ])

I built this aggregation using the Mongo compass program which allows you to see your aggregations working live by building it step by step.

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