In MongoDB, if you want to sort documents in a collection by date, you can use the .sort() method to achieve this. Sorting can be performed in ascending or descending order; for ascending order, specify 1, and for descending order, specify -1.
Suppose you have a collection named orders where each document contains an orderDate field storing the order date. To sort these orders in ascending order by date, use the following MongoDB query command:
javascriptdb.orders.find().sort({orderDate: 1})
Conversely, if you want to sort by date in descending order, you can write:
javascriptdb.orders.find().sort({orderDate: -1})
Example:
Suppose the orders collection contains the following documents:
json{ "_id": 1, "product": "Apple", "orderDate": ISODate("2022-03-15T00:00:00Z") } { "_id": 2, "product": "Banana", "orderDate": ISODate("2022-03-14T00:00:00Z") } { "_id": 3, "product": "Cherry", "orderDate": ISODate("2022-03-16T00:00:00Z") }
If you execute the ascending order sort query:
javascriptdb.orders.find().sort({orderDate: 1})
The result will be:
json{ "_id": 2, "product": "Banana", "orderDate": ISODate("2022-03-14T00:00:00Z") } { "_id": 1, "product": "Apple", "orderDate": ISODate("2022-03-15T00:00:00Z") } { "_id": 3, "product": "Cherry", "orderDate": ISODate("2022-03-16T00:00:00Z") }
This sorts the documents in ascending order based on the orderDate field. It is very useful for handling time-series data, generating reports, or displaying results in user interfaces.