GetTimeStamp in MongoDB using ObjectId
Today in this article, we will see how to GetTimeStamp in MongoDB using ObjectId using Mongoshell or CLI tools
ObjectId is the 12-byte element consisting of the below fields,
- timestamp value,
- a random value
- incremental counter
MongoDB uses the _id field as ObjectId, this Id has few behavioral characteristics and it is explained below,
- MongoDB database automatically generates _id the field for insertion.
- This field is unique for every document inserted into the collection.
- _id field is automatically indexed and the index is unique.
We can very much use getTimestamp() method which returns the timestamp portion( 4 bytes) of the ObjectId
ObjectId(“62ac091058c3f35ca07859a9”).getTimestamp()
ISODate(“2022-06-17T04:54:40Z”)
Few other examples,
> ObjectId("5a682326bf8380e6e6584ba5").getTimestamp()
ISODate("2018-01-24T06:09:42Z")
> ObjectId.fromDate(ISODate("2018-01-24T06:09:42Z"))
ObjectId("5a6823260000000000000000")
References:
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.