Sometimes, we want to sort a collection by date in MongoDB.
In this article, we’ll look at how to sort a collection by date in MongoDB.
How to sort a collection by date in MongoDB?
To sort a collection by date in MongoDB, we can use the sort method.
For instance, we write
collection.find().sort({
datefield: -1
}, (err, cursor) => {
//...
});
to call sort to sort dateField in descending order by setting dateField to -1.
Conclusion
To sort a collection by date in MongoDB, we can use the sort method.