MongoDB ObjectId to Timestamp and Timestamp to ObjectId Converter

Connect with

MongoDB objectId
How to convert MongoDB ObjectId to Timestamp and timestamp to MongoDB ObjectId. This usually used by the admin in their day-to-day admin tasks.

Overvie of mongoDB objectId to Timestamp

In MongoDB, when you insert any document, by default _id field added by DB engine while inserting if not present in the document. And one interesting thing is, the value of _id consists of timestamp too, which means its unique key generated by the MongoDB engine. _id has much more that than timestamp to maintain the uniqueness of the key.

You know, in any database, either Relational or NoSQL DB, in a table/collection, there is a primary key for each row/document which is always unique.

You can query, which means you can apply date-range query on _id document key which is indexed in MongoDB by default. If you change provided any value for _id then MongoDB will not generate the value of _id on behalf of yours. Meaning that then you can’t query like date range, but still you can query whatever data you have provided.

For more details about mongodb _id, you can visit MongoDB ObjectId

For online use you can use TimeStamp to ObjectId and ObjectId to timeStamp

From the mongo shell, you can use getTimestamp() to retrieve the timestamp from the ObjectId, but there’s no built in function to generate an ObjectId from a timestamp. However, you can use this utility tool to convert from timestamp (date with time) to ObjectId and ObjectId to timestamp.

You can visit our another post related to _id:

Why generate an ObjectId from a timestamp?

To query documents by creation date. this is essential to know about mongodb objectId to timestamp and timestamp to objectId in mongoDB.

e.g. to find all users created after 2017-12-01 , here users is a collection in mongodb

db.users.find({_id: {$gt: ObjectId("5a204e280000000000000000")}})

Javascript functions to generage objectId from date

var objectIdFromDate = function (date) {
	return Math.floor(date.getTime() / 1000).toString(16) + "0000000000000000";
};

Javascript functions to generate date from objectId

var dateFromObjectId = function (objectId) {
  return new Date(parseInt(objectId.substring(0, 8), 16) * 1000);
};


	

File: objectId-timestamp.html



(You can paste into mongo shell)
Time (UTC)

Year (YYYY)
Month (1 - 12)
Date (1 - 31)
Hours
Minutes
Seconds
ISO Timestamp

CSS code


Happy learning 🙂


Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *