Categories
JavaScript Answers

How to sort a collection by date in MongoDB?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *