0

I have a Post model that has a likes array that contains the ObjectId of the user that liked the Post, I would like to sort Posts based on how many likes they have received.

I'm sure I would use $size, $sort and aggregate, but everything I have tried doesn't seem to work. Can you use $size within $sort? What would be the correct way of doing this? and is there a specific way of doing it with mongoose?

1 Answer 1

1
db.collection.aggregate([
  {
    $set: {
      size: { $size: "$likes" }
    }
  },
  {
    $sort: {
      size: -1
    }
  }
])

mongoplayground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.