Sort By Date
In this final step, you'll learn how to sort documents by date in MongoDB. We'll continue using the datelab
database from previous steps and explore various sorting techniques.
First, let's ensure we're in the right database:
use datelab
Let's add a few more events to create a diverse dataset:
db.events.insertMany([
{
event_name: "AI Summit",
date: new Date("2024-10-15T09:00:00Z"),
category: "Technology"
},
{
event_name: "Blockchain Workshop",
date: new Date("2024-05-22T14:30:00Z"),
category: "Finance"
},
{
event_name: "Cloud Computing Expo",
date: new Date("2024-03-10T11:15:00Z"),
category: "IT"
}
])
Now, let's explore different ways to sort documents by date:
- Sort events in ascending order (earliest to latest):
db.events.find().sort({ date: 1 })
- Sort events in descending order (latest to earliest):
db.events.find().sort({ date: -1 })
- Combine sorting with filtering:
db.events.find({
category: "Technology"
}).sort({ date: 1 })
- Advanced sorting with multiple criteria:
db.events.find().sort({
category: 1, // Sort by category first
date: -1 // Then by date in descending order
})
Let's verify our sorting results:
db.events.find({}, {
event_name: 1,
date: 1,
category: 1
}).sort({ date: 1 })
Example output:
[
{
_id: ObjectId("..."),
event_name: 'Cloud Computing Expo',
date: 2024-03-10T11:15:00.000Z,
category: 'IT'
},
{
_id: ObjectId("..."),
event_name: 'Blockchain Workshop',
date: 2024-05-22T14:30:00.000Z,
category: 'Finance'
},
{
_id: ObjectId("..."),
event_name: 'AI Summit',
date: 2024-10-15T09:00:00.000Z,
category: 'Technology'
}
]
Sorting key points:
1
: Ascending order
-1
: Descending order
- Can sort by multiple fields
- Works with dates, strings, numbers