This operator will set the value of a given field to the current date as a date or timestamp data type.
Operator Syntax
The following shows the syntax of the $currentDate operator:
You can specify the typeSpecification parameter as a:
- Boolean true to insert the value of the $currentDate field as Date type.
- A document {$type: “timestamp”} or {$type: “date”} to manually specify the data type of the field. The value “timestamp” or “date” is case sensitive. Use the lowercase equivalent values.
Let us illustrate how to use this operator.
Practical Example
Let us start by creating a sample collection for testing purposes.
We can then create a document as shown in the code below:
Fetch the documents:
Output:
{
"_id" : 0.0,
"username" : "username1",
"modified" : Timestamp(1663761552, 3)
}
We can then update the value of modified field to current date as shown in the query:
{_id: 0},
{$currentDate: {
modified: true,
}
}
)
The query above should update the modified field to the current date. We can verify as shown:
Output:
{
"_id" : 0.0,
"username" : "username1",
"modified" : ISODate("2022-09-21T12:08:43.574+0000")
}
In this case, the $currentDate parameter will insert the date as a Date type.
To insert the current date as a timestamp, we can run the parameter:
{ _id: 0 },
{
$currentDate: {
modified: { $type: "timestamp" },
}
}
)
This should update the modified field to the current date as a timestamp type.
Output:
"_id" : 0.0,
"username" : "username1",
"modified" : Timestamp(1663762490, 1)
}
Conclusion
In this post, we discussed how to use the $currentDate operator in MongoDB documents. This operator allows you to insert the value of a field as a date type or timestamp.