MongoDB

MongoDB Current Date

When working with MongoDB documents, you may encounter a scenario where you need to create a field holding the current date. Instead of manually adding the date or timestamp value to the field, MongoDB provides us with the $currentDate operator.

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:

{ $currentDate: { <field1>: <typeSpecification1>, ... } }

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.

db.createCollection("users")

We can then create a document as shown in the code below:

db.users.insertOne({_id: 0, username: "username1", modified: Timestamp(1663761552, 3)})

Fetch the documents:

db.users.find({})

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:

db.users.updateOne(

{_id: 0},

{$currentDate: {

modified: true,

}

}

)

The query above should update the modified field to the current date. We can verify as shown:

db.users.find({})

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:

db.users.updateOne(
    { _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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list