Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!