Introduction to MongoDB $currentDate Operator
Mongodb is a document-oriented database that supports many different operators for querying and updating documents. One of these operators is the $currentDate
operator, which can set a date field in a document to the current date or time.
Syntax
The syntax of the $currentDate
operator is as follows:
{ $currentDate: { <field>: <typeSpecification>, ... } }
where <field>
specifies the name of the field to be updated, and <typeSpecification>
specifies the type of date to be set. <typeSpecification>
can be a boolean value or a date type string, such as:
true
to set the date to the current timestamp.{ $type: "date" }
to set the date to the current date.
Use Cases
The $currentDate
operator can be used in any update operation, such as updateOne
, updateMany
, and replaceOne
.
When you want to automatically set a date field to the current date or time in an update operation, you can use the $currentDate
operator. For example, you can add a lastLogin
field to a user document and use $currentDate
to set it to the current date when the user logs in.
Examples
Suppose we have a collection named users
with the following documents:
{
"_id": ObjectId("602f5a00b5ff5e89d728c166"),
"username": "alice",
"email": "[email protected]",
"lastLogin": ISODate("2022-02-23T10:23:51.000Z")
},
{
"_id": ObjectId("602f5a11b5ff5e89d728c167"),
"username": "bob",
"email": "[email protected]",
"lastLogin": ISODate("2022-02-22T08:15:33.000Z")
}
Now, we want to update alice
’s lastLogin
field to the current date. We can use the following code:
db.users.updateOne({ username: "alice" }, { $currentDate: { lastLogin: true } })
After running the above code, the users
collection will become:
{
"_id": ObjectId("602f5a00b5ff5e89d728c166"),
"username": "alice",
"email": "[email protected]",
"lastLogin": ISODate("2023-03-09T05:42:58.000Z")
},
{
"_id": ObjectId("602f5a11b5ff5e89d728c167"),
"username": "bob",
"email": "[email protected]",
"lastLogin": ISODate("2022-02-22T08:15:33.000Z")
}
As you can see, alice
’s lastLogin
field has been updated to the current timestamp.
Conclusion
The $currentDate
operator is a very useful tool that can automatically set a date field to the current date or time in an update operation.