You must have seen that in all our articles we have mentioned the date of publishing the article right after the title. Let’s say you are also developing an application and using MongoDB as the database for your app. Now you also want to create functionality to track the current date when a particular event occurs, let’s say when data is inserted into a collection.
For instance, when someone writes an article and clicks the “Publish” button, the data related to the article, like – title, content, images, etc. gets saved in the MongoDB database, but you also want to save the present date with them. You can easily do this by writing a single line of code implementing the $currentDate operator.
$currentDate is one of the extremely unique and useful operators in MongoDB that allows users to set a field value as the current date. In this article, we will understand the $currentDate operator, and its syntax, and demonstrate it using bits of examples. Let’s get started.
Introduction to MongoDB $currentDate Operator
The $currentDate operator is mainly used with update methods like update(), updateOne(), etc or insert methods like insert(), insertOne(), etc, to set the value of a field of a document to the current date & time. It can be set as a Timestamp or a Date type.
The $currentDate operator can also be used within the aggregation pipeline, mainly in stages like $addFields or $set, etc.
The value set by this method by default is of Date type (standard ISO date format), however, you can even set a Timestamp type value by explicitly stating it.
Syntax of MongoDB $currentDate Operator
Let us take a quick look at the $currentDate syntax in MongoDB when using the Mongo shell.
{ $currentDate: { field: true} }
Important: We must set the field as true to allow the operator to set the current date.
Syntax for specifying Date or Timestamp Type:
To specify the type (format) of the date value, you can state as { $type: “timestamp” } or { $type: “date” } as per your needs. Make sure you only use lowercase letters as the operator is case-sensitive.
{
$currentDate: {
field: { $type: "timestamp" }
}
Or
{
$currentDate: {
field: { $type: "date" }
}
Note: If the given field does not exist, the operator adds it by itself and sets the value as the current date.
Example of MongoDB $currentDate Operator
Let us now look at some practical examples of using the $currentDate operator in the MongoDB shell.
Setup:
1. Start the MongoDB shell.
2. Execute the following commands to list all the available databases & move into one of them.
show dbs
use catShop
Here we are using the “carShop” database where we have already created a collection “cats” having different content for demonstration.
3. Execute the below query to display documents from a collection.
> db.cats.find().pretty()
{
"_id" : ObjectId("602eb6c728ff814b64eb3411"),
"name" : "Stephanie",
"age" : 22,
"breed" : "Persian Cat",
"personality" : {
"dogFriendly" : true,
"childFriendly" : true
},
"moreDetails" : {
"cost" : 30000
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602eb73728ff814b64eb3412"),
"name" : "Whiskers",
"age" : 4,
"breed" : "Scottish Fold",
"personality" : {
"dogFriendly" : false,
"childFriendly" : true
},
"moreDetails" : {
"cost" : 30000
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602eb84628ff814b64eb3413"),
"name" : "Krissy",
"age" : 6,
"breed" : "Turkish Angora",
"personality" : {
"dogFriendly" : true,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebc5ea78db75e09057cd0"),
"name" : "Cassy",
"age" : 16,
"breed" : "Japanese Angora",
"personality" : {
"dogFriendly" : true,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebc9da78db75e09057cd1"),
"name" : "Shane",
"age" : 11,
"breed" : "Bobtail",
"personality" : {
"dogFriendly" : false,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebed7a78db75e09057cd2"),
"name" : "Phoebe",
"age" : 21,
"breed" : "Bobtail",
"personality" : {
"dogFriendly" : false,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
This is the collection we will work with to demonstrate the use of the $currentDate operator.
In the above query, we have used the pretty() function which is used in MongoDB to format the query results with a proper indentation and produce readable output that looks like JSON which makes it easier to view and understand.
Example
In this example, let’s try to insert an embedded document that doesn’t exist in the above collection. Let’s say we want to set an “adoptionDate” field inside the “moreDetails” field assuming that all the cats in the collection got adopted today.
> db.cats.updateMany({}, {$currentDate: {"moreDetails.adoptionDate": true}})
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }
> db.cats.find().pretty()
{
"_id" : ObjectId("602eb6c728ff814b64eb3411"),
"name" : "Stephanie",
"age" : 22,
"breed" : "Persian Cat",
"personality" : {
"dogFriendly" : true,
"childFriendly" : true
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.933Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602eb73728ff814b64eb3412"),
"name" : "Whiskers",
"age" : 4,
"breed" : "Scottish Fold",
"personality" : {
"dogFriendly" : false,
"childFriendly" : true
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.938Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602eb84628ff814b64eb3413"),
"name" : "Krissy",
"age" : 6,
"breed" : "Turkish Angora",
"personality" : {
"dogFriendly" : true,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.938Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebc5ea78db75e09057cd0"),
"name" : "Cassy",
"age" : 16,
"breed" : "Japanese Angora",
"personality" : {
"dogFriendly" : true,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.938Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebc9da78db75e09057cd1"),
"name" : "Shane",
"age" : 11,
"breed" : "Bobtail",
"personality" : {
"dogFriendly" : false,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.939Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebed7a78db75e09057cd2"),
"name" : "Phoebe",
"age" : 21,
"breed" : "Bobtail",
"personality" : {
"dogFriendly" : false,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.939Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
In the above output, you can actually see that the “adoptionDate” field inside “moreDetails” has been created and contains a date object having the current date & time as a string in ISODate format.
Setting Date or Timestamp Type in $currentDate Operator
Let us now try to use the $type operator to specify the type that we have learned in the beginning. Let’s try passing both “date” and “timestamp” to see how the result varies. For demonstration, we will use the same collection as in the previous example.
Note: We do not recommend using the $type operator, instead use the default type as it is standard for many applications.
Setting Date Type
Before setting the Date type, let’s see its format.
Formate of Date Type:
YYYY-MM-DDTHH:MM:SSZ
where,
- YYYY denotes the year,
- MM denotes the month,
- DD denotes the day,
- T denotes the separator,
- HH denotes the hour (24-hour format),
- MM denotes the minute,
- SS denotes the second (not millisecond),
- Z denotes UTC (Universal Time Coordinated).
Let’s now set the Date data type by defining { $type: “date” }.
> db.cats.updateMany({}, {$currentDate: {"moreDetails.adoptionDate": {$type: "date"}}})
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }
> db.cats.find().pretty()
{
"_id" : ObjectId("602eb6c728ff814b64eb3411"),
"name" : "Stephanie",
"age" : 22,
"breed" : "Persian Cat",
"personality" : {
"dogFriendly" : true,
"childFriendly" : true
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.933Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602eb73728ff814b64eb3412"),
"name" : "Whiskers",
"age" : 4,
"breed" : "Scottish Fold",
"personality" : {
"dogFriendly" : false,
"childFriendly" : true
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.938Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602eb84628ff814b64eb3413"),
"name" : "Krissy",
"age" : 6,
"breed" : "Turkish Angora",
"personality" : {
"dogFriendly" : true,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.938Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebc5ea78db75e09057cd0"),
"name" : "Cassy",
"age" : 16,
"breed" : "Japanese Angora",
"personality" : {
"dogFriendly" : true,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.938Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebc9da78db75e09057cd1"),
"name" : "Shane",
"age" : 11,
"breed" : "Bobtail",
"personality" : {
"dogFriendly" : false,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.939Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebed7a78db75e09057cd2"),
"name" : "Phoebe",
"age" : 21,
"breed" : "Bobtail",
"personality" : {
"dogFriendly" : false,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : ISODate("2021-10-28T21:47:06.939Z")
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
The output does not look different from the previous example where we have not used the $type operator, i.e., 0 documents changed because the “date” type is also the default behavior of the $currentDate operator and hence the operator returned this exact output previously as well.
Setting Timestamp Type
Let’s now see how to set the Timestamp type.
A simple definition of Timestamp is a 64-bit integer representing the number of milliseconds since the UNIX epoch, i.e., January 1, 1970, 00:00:00 GMT.
> db.cats.updateMany({}, {$currentDate: {"moreDetails.adoptionDate": {$type: "timestamp"}}})
{ "acknowledged" : true, "matchedCount" : 6, "modifiedCount" : 6 }
> db.cats.find().pretty()
{
"_id" : ObjectId("602eb6c728ff814b64eb3411"),
"name" : "Stephanie",
"age" : 22,
"breed" : "Persian Cat",
"personality" : {
"dogFriendly" : true,
"childFriendly" : true
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : Timestamp(1635457867, 1)
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602eb73728ff814b64eb3412"),
"name" : "Whiskers",
"age" : 4,
"breed" : "Scottish Fold",
"personality" : {
"dogFriendly" : false,
"childFriendly" : true
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : Timestamp(1635457867, 2)
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602eb84628ff814b64eb3413"),
"name" : "Krissy",
"age" : 6,
"breed" : "Turkish Angora",
"personality" : {
"dogFriendly" : true,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : Timestamp(1635457867, 3)
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebc5ea78db75e09057cd0"),
"name" : "Cassy",
"age" : 16,
"breed" : "Japanese Angora",
"personality" : {
"dogFriendly" : true,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : Timestamp(1635457867, 4)
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebc9da78db75e09057cd1"),
"name" : "Shane",
"age" : 11,
"breed" : "Bobtail",
"personality" : {
"dogFriendly" : false,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : Timestamp(1635457867, 5)
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
{
"_id" : ObjectId("602ebed7a78db75e09057cd2"),
"name" : "Phoebe",
"age" : 21,
"breed" : "Bobtail",
"personality" : {
"dogFriendly" : false,
"childFriendly" : false
},
"moreDetails" : {
"cost" : 30000,
"adoptionDate" : Timestamp(1635457867, 6)
},
"likes" : [
"fish",
"milk",
"chicken",
"blankets"
]
}
Here, you can see the difference in the data type. The date is stored as a Timestamp object having time in seconds with an incrementing counter rather than in the standard ISO date format.
Conclusion
In this article, we have learned to use the $currentDate to perform an operation on documents to set the value of a field to the current date when working with MongoDB. We can use this to either update the date or create a new date and insert it into the specified field by creating it. The date can be set as a Date (standard ISO date format) or Timestamp by using { $type: “date” } or { $type: “timestamp” } respectively. This operator may help in various cases where we need to track the time of interaction with data in the MongoDB database. For instance, when a document is created, updated, deleted, etc. Hope you enjoyed reading the content.
Read More: gte and lte Operators in MongoDB