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

106
Vistas
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 Respuestas
Responde la pregunta

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 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