0

This is my Mongodb data...

Data

I'm using this node/mongoose script to get a particular exam sorted by the score.

User.find("completedExams.exam": "test-1").sort({'completedExams.score': -1}).select({'completedExams.$': 1, name: 1}).limit(5).exec(
  function(err, allScores) {
    if (err) res.status(500).send(err);
    res.json(allScores);
  });

But I'm getting this. it's not sorting by score

Output

Saeid Amini
  • 1,313
  • 5
  • 16
  • 26

1 Answers1

0

I have tried this with aggregation. This is plain mongo query. I hope you can translate it into nodejs. Here is the query :-

db.collection.aggregate([
  {
    "$unwind": "$completedExams"
  },
  {
    "$match": {
      "completedExams.exam": "test-1"
    }
  },
  {
    "$sort": {
      "completedExams.score": -1
    }
  }
])

And here is link to Mongo Playground

Hope this is what you were looking for.

wak786
  • 1,562
  • 1
  • 8
  • 12