'How to sort order by descending in mongo query? [closed]

I want to show recently added data in the collection from MongoDB.

How can I do that?



Solution 1:[1]

You can use auto-generated-createdat-and-updatedat-fields-in-mongodb, then use the $orderby operator to order it descending. It may be worth it to add an index on those fields if you expect your table to grow.

db.collection.find().sort( { age: -1 } )

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bruno Farias