Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo sort descending

I am having trouble sorting in descending order with mongo.

Example: I have multiple entries with the field score.

{_id:1, score:0}
{_id:2, score:1}
{_id:3, score:-1}

When i run the following command

db.entries.find({}).sort({score:-1});

It ranks in the following order:

{_id:2, score:1}
{_id:3, score:-1}
{_id:1, score:0}

Any idea why this is happening, and is there any fix?

like image 664
Manak Kapoor Avatar asked Feb 03 '26 08:02

Manak Kapoor


1 Answers

Try this

db.entries.find().sort({score:-1}) 

instead of

db.entries.find({}).sort({score:-1})
like image 150
sorma Gupta Avatar answered Feb 05 '26 00:02

sorma Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!