- Reference >
- Operators >
- Update Operators >
- Field Update Operators >
- $currentDate
$currentDate¶
On this page
Definition¶
-
$currentDate
¶ The
$currentDate
operator sets the value of a field to the current date, either as a Date or a timestamp. The default type is Date.The
$currentDate
operator has the form:<typeSpecification>
can be either:- a boolean
true
to set the field value to the current date as a Date, or - a document
{ $type: "timestamp" }
or{ $type: "date" }
which explicitly specifies the type. The operator is case-sensitive and accepts only the lowercase"timestamp"
or the lowercase"date"
.
To specify a
<field>
in an embedded document or in an array, use dot notation.- a boolean
Behavior¶
If the field does not exist, $currentDate
adds the field to a
document.
Example¶
Create a sample collection customers
with the following document:
The following operation updates the lastModified
field to the
current date, the "cancellation.date"
field to the current timestamp
as well as updating the status
field to "D"
and the
"cancellation.reason"
to "user request"
.
After the operation, you can query the collection to verify the update:
The updated document would resemble:
Aggregation Alternative to $currentDate
¶
Starting in version 4.2, update methods can accept an aggregation pipeline. As
such, the previous example can be rewritten as the following using the
aggregation stage $set
and the aggregation variables
NOW
(for the current datetime) and CLUSTER_TIME
(for the current timestamp):
Tip
- To access aggregation variables, prefix the variable with double
dollar signs
$$
and enclose in quotes. CLUSTER_TIME
is available only on replica sets and sharded clusters.- The
NOW
andCLUSTER_TIME
values remain the same throughout the pipeline.
After the operation, you can query the collection to verify the update:
The query should return the following document: