Introduction
In this lab, you will learn how to work with dates in MongoDB. You will practice inserting documents with date values, querying for documents within specific date ranges, formatting date fields for display, updating existing date fields, and sorting collections by date. This lab provides a comprehensive, hands-on guide to MongoDB's date-related functionalities, which are essential for managing time-series data, scheduling, and logging applications.
Insert Documents with Date Values
In this first step, you will connect to the MongoDB server and insert several documents containing date values. This will form the foundation for the queries and operations you will perform in later steps.
First, open the MongoDB shell by running the mongosh command in your terminal. This will connect you to the running MongoDB instance.
mongosh
Once inside the shell, you will see a prompt like test>. Let's switch to a new database named datelab. If the database does not exist, MongoDB will create it for you when you first insert data.
use datelab
Now, you will insert three documents into a new collection called events. Each document will represent an event and will include a date. MongoDB stores dates as BSON Date objects, which you can create using the new Date() constructor.
Insert the following documents one by one. The first uses an ISO-8601 date string, the second uses the current date and time, and the third uses a Unix timestamp in milliseconds.
db.events.insertOne({
event_name: "Conference",
date: new Date("2024-06-15T10:30:00Z")
})
db.events.insertOne({
event_name: "System Maintenance",
timestamp: new Date()
})
db.events.insertOne({
event_name: "Project Deadline",
timestamp: new Date(1718476800000)
})
After inserting the documents, you can verify that they were added correctly by using the find() method, which retrieves all documents from the collection.
db.events.find()
Your output should look similar to this, although the _id values and the timestamp for "System Maintenance" will be different for you.
[
{
_id: ObjectId("65d38f8a1c2d3e4f5a6b7c8d"),
event_name: 'Conference',
date: ISODate('2024-06-15T10:30:00.000Z')
},
{
_id: ObjectId("65d38f9c1c2d3e4f5a6b7c8e"),
event_name: 'System Maintenance',
timestamp: ISODate('2024-02-19T14:55:24.123Z')
},
{
_id: ObjectId("65d38fb11c2d3e4f5a6b7c8f"),
event_name: 'Project Deadline',
timestamp: ISODate('2024-06-15T18:00:00.000Z')
}
]
You have now successfully inserted documents with date values. In the next step, you will learn how to query these documents based on their dates.
Query Documents by Date Range
With data in your collection, you can now perform queries to find documents that fall within specific date ranges. This is a common requirement for applications that handle scheduled events, logs, or time-sensitive data.
First, let's add more events to our collection to make the queries more interesting. We will use the insertMany() method to add three documents at once.
db.events.insertMany([
{
event_name: "Summer Conference",
date: new Date("2024-07-15T09:00:00Z")
},
{
event_name: "Winter Workshop",
date: new Date("2024-01-20T14:30:00Z")
},
{
event_name: "Spring Meetup",
date: new Date("2024-04-10T11:15:00Z")
}
])
Now you have a total of six events. Let's find all events that occurred after June 1, 2024. To do this, you will use the "greater than" operator, $gt.
db.events.find({
date: { $gt: new Date("2024-06-01") }
})
Next, let's find all events that occurred in the first half of 2024, specifically between January 1st and June 1st. You can combine the "greater than or equal to" ($gte) and "less than" ($lt) operators for this.
db.events.find({
date: {
$gte: new Date("2024-01-01"),
$lt: new Date("2024-06-01")
}
})
The query will return the "Winter Workshop" and "Spring Meetup" events. The output should look like this:
[
{
_id: ObjectId("65d392a11c2d3e4f5a6b7c91"),
event_name: 'Winter Workshop',
date: ISODate('2024-01-20T14:30:00.000Z')
},
{
_id: ObjectId("65d392a11c2d3e4f5a6b7c92"),
event_name: 'Spring Meetup',
date: ISODate('2024-04-10T11:15:00.000Z')
}
]
These examples demonstrate how to use comparison operators ($gt, $gte, $lt, $lte) to effectively filter documents based on date fields.
Format Date Output with Aggregation
Often, you need to display dates in a specific, human-readable format. MongoDB's aggregation framework provides powerful tools for this. In this step, you will use the $dateToString operator to format your date fields.
The aggregation framework processes documents through a pipeline of stages. We will use a $project stage to reshape our documents and create a new, formatted date field.
Let's format the date field of our events into a YYYY-MM-DD format. This query will process only the documents that have a date field.
db.events.aggregate([
{
$project: {
event_name: 1,
formatted_date: {
$dateToString: {
format: "%Y-%m-%d",
date: "$date"
}
}
}
}
])
Let's break down this command:
db.events.aggregate([...]): Initiates an aggregation pipeline on theeventscollection.$project: A stage that reshapes documents. We include theevent_nameand create a new fieldformatted_date.$dateToString: An operator that converts a date object into a string.format: "%Y-%m-%d": Specifies the output format.%Yis the year,%mis the month, and%dis the day.date: "$date": Specifies the input date field from the original document. The$prefix indicates a field path.
The output will show the original event name and the newly formatted date string. Note that documents without a date field (like "System Maintenance") will be omitted from the result.
[
{ _id: ObjectId("..."), event_name: 'Conference', formatted_date: '2024-06-15' },
{ _id: ObjectId("..."), event_name: 'Summer Conference', formatted_date: '2024-07-15' },
{ _id: ObjectId("..."), event_name: 'Winter Workshop', formatted_date: '2024-01-20' },
{ _id: ObjectId("..."), event_name: 'Spring Meetup', formatted_date: '2024-04-10' }
]
You can also extract individual components of a date, such as the year or month, using operators like $year and $month.
db.events.aggregate([
{
$project: {
event_name: 1,
year: { $year: "$date" },
month: { $month: "$date" },
day: { $dayOfMonth: "$date" }
}
}
])
This gives you fine-grained control over how you process and present date information.
Update Date Fields
Your data is not always static. You may need to update date fields, such as rescheduling an event or adding a modification timestamp. In this step, you will learn how to update date fields using various update operators.
First, let's reschedule the "Conference" event to a new date. We will use the updateOne() method to target a single document and the $set operator to change its date field.
db.events.updateOne(
{ event_name: "Conference" },
{
$set: {
date: new Date("2024-09-01T10:00:00Z"),
status: "Rescheduled"
}
}
)
Now, let's perform a bulk update. We will mark all events that occurred before May 1, 2024, as "Archived". We will also add a new field, last_modified, to record when this update happened. The updateMany() method will modify all matching documents, and the $currentDate operator is perfect for setting a field to the current server time.
db.events.updateMany(
{ date: { $lt: new Date("2024-05-01") } },
{
$set: { status: "Archived" },
$currentDate: { last_modified: true }
}
)
Let's verify the changes by retrieving all documents. The .pretty() method is deprecated, so we will just use find().
db.events.find()
You will see that the "Conference" has a new date and status. The "Winter Workshop" and "Spring Meetup" are now marked as "Archived" and have a last_modified timestamp.
Example output for an archived event:
{
"_id" : ObjectId("..."),
"event_name" : "Winter Workshop",
"date" : ISODate("2024-01-20T14:30:00Z"),
"status" : "Archived",
"last_modified" : ISODate("2024-02-19T15:10:00Z")
}
These operations show how you can precisely modify date-related information in your documents.
Sort Documents by Date
The final fundamental operation you will learn is sorting. Displaying events in chronological order is a common requirement. MongoDB makes it easy to sort your query results by any field, including dates.
To sort documents, you append the .sort() method to a find() query. The sort() method takes a document that specifies the field to sort by and the sort order. A value of 1 indicates ascending order (earliest to latest), and -1 indicates descending order (latest to earliest).
Let's retrieve all events sorted by their date in ascending order.
db.events.find().sort({ date: 1 })
This will list the events from the "Winter Workshop" (earliest) to the "Summer Conference" (latest). Documents without a date field will be sorted first if they are included in the query.
Now, let's sort the events in descending order to see the most recent events first.
db.events.find().sort({ date: -1 })
You can also combine sorting with filtering. For example, let's find all events that are not archived and sort them by date.
db.events.find({ status: { $ne: "Archived" } }).sort({ date: 1 })
The output will show the non-archived events in chronological order.
[
{
_id: ObjectId("..."),
event_name: 'System Maintenance',
timestamp: ISODate("...")
},
{
_id: ObjectId("..."),
event_name: 'Project Deadline',
timestamp: ISODate('2024-06-15T18:00:00.000Z')
},
{
_id: ObjectId("..."),
event_name: 'Summer Conference',
date: ISODate('2024-07-15T09:00:00.000Z')
},
{
_id: ObjectId("..."),
event_name: 'Conference',
date: ISODate('2024-09-01T10:00:00.000Z'),
status: 'Rescheduled'
}
]
Sorting is a crucial tool for presenting time-ordered data in a meaningful way. When you are finished, you can exit the MongoDB shell by typing exit or pressing Ctrl+D.
Summary
In this lab, you have learned the fundamental techniques for working with dates in MongoDB. You started by inserting documents with date values using different formats. You then practiced querying documents based on date ranges with comparison operators. After that, you explored the aggregation framework to format date fields for better readability. You also learned how to update date fields and add modification timestamps. Finally, you mastered sorting collections by date to present data in chronological order. These skills are essential for any developer working with time-based data in MongoDB.

