MongoDB: How to Sort Documents By Date In Database
Published on Aug. 22, 2023, 12:12 p.m.
In addition, you can use the following methods to sort documents by a date field in database :
Sort by Date Ascending .
db.sales.find().sort({"date_field": 1})
Sort by Date Descending
db.sales.find().sort({"date_field": -1})
db.sales.insertOne({day: new Date("2020-01-20"), amount: 40})
db.sales.insertOne({day: new Date("2020-01-21"), amount: 32})
db.sales.insertOne({day: new Date("2020-01-22"), amount: 19})
db.sales.insertOne({day: new Date("2020-01-23"), amount: 29})