Introduction
In the realm of databases, recording and manipulating dates and times are common tasks that developers deal with on a regular basis. MongoDB, being a widely used NoSQL database, provides utilities for handling date and time data types. In this tutorial, you will learn how to deal with the aspects of getting the current date and time in MongoDB, tailored for beginners to more advanced users.
MongoDB stores dates in UTC by default and the Date object exposed in the MongoDB shell is equivalent to the JavaScript Date object. This tutorial will guide you through how to manipulate and retrieve date and time data in MongoDB using various examples.
Basics of Date in MongoDB
Let’s start by looking at the simplest method to get the current date and time in MongoDB. When you want to create a new Date object representing the current time, you simply use the new Date() expression:
db.collection.insertOne({
"event": "documentCreation",
"createdAt": new Date()
});
This will insert a new document into ‘collection’ where the createdAt
field will be stamped with the current UTC time.
MongoDB Date objects can also be queried. Let’s retrieve a document and print its date and time:
db.collection.find({ "event": "documentCreation" }).forEach(function(doc) {
print(doc.createdAt);
});
Handy for when you want to see the creation time for documents with a particular event.
Manipulating Date and Time Values
You can manipulate the date and time values to subtract or add time or even to directly set a component of a Date object, such as the day, month, or year. Here is an example where we add one day to the current date:
// Get the current date.
var currentDate = new Date();
// Add one day to the current date.
currentDate.setDate(currentDate.getDate() + 1);
// Update one document in the collection to set "tomorrow" field to the new date.
db.collection.updateOne({}, {$set: {"tomorrow": currentDate}});
This code fetches the current date and then utilizes the setDate() and getDate() methods to manipulate the date. If you need a more precise duration like adding hours, minutes or even milliseconds, you could use methods like setHours(), setMinutes(), and setMilliseconds().
Aggregation and Dates
In more complex scenarios, you might wish to perform aggregation operations involving dates. MongoDB’s aggregation framework provides a suite of date operators that can be used to extract components of a date, compare dates, and format dates.
Take this scenario where you want to group your collection’s documents by year of creation:
db.collection.aggregate([
{
$group: {
_id: { year: { $year: "$createdAt" } },
count: { $sum: 1 }
}
}
]);
This will give you a count of documents created per year. The $year operator extracts the year part of the date from the createdAt
field.
Using the $currentDate Operator
MongoDB offers the $currentDate operator which can set the value of a field to the current date, either as a date or a timestamp:
db.collection.updateMany({}, { $currentDate: { lastModified: true } });
This will update the lastModified
field in every document within ‘collection’ to the current date and time.
Operating Within Different Timezones
Since MongoDB stores dates in UTC by default, you may often find yourself needing to interact with dates in different time zones. Since MongoDB version 3.6, it is possible with the $dateToParts and $dateFromString aggregation pipeline operators.
Here’s an example of how to extract the date in your local timezone:
db.collection.aggregate([
{
$project: {
dateLocal: {
$dateToString: {
format: "%Y-%m-%dT%H:%M:%S:%LZ",
date: "$created_at",
timezone: "America/New_York"
}
}
}
}
]);
This projection takes the created_at
field and converts it to string format considering the timezone specified.
Handling Date in Queries
Another typical requirement is to query documents based on date conditions. Here is an example where you want to find documents created after a certain date:
var startDate = new Date("January 01, 2025");
db.collection.find({ "createdAt": { $gte: startDate }});
Here, $gte is a query operator that stands for “greater than or equal to”. This query will retrieve all documents created on or after January 1, 2021.
Advanced Date Operations
MongoDB is very rich in date operations. For instance, it provides an operator named $dateDiff which debuted in version 5.0 to calculate the difference between two dates.
An interesting use case could be calculating the age of a document in days:
db.collection.aggregate([
{
$set: {
ageInDays: {
$dateDiff: {
startDate: "$createdAt",
endDate: "$currentDate",
unit: "day"
}
}
}
}
]);
Here, $currentDate provided above and $dateDiff are combined to compute the difference in days between the creation date of the document and the current date.
Conclusion
This tutorial has taken you from the very basics of date and time handling in MongoDB to some more advanced operations. Understanding date and time manipulation is crucial in many applications, and with the examples provided, you should be well-equipped to tackle various temporal tasks within your MongoDB instances.