MongoDB ObjectId to Timestamp and Timestamp to ObjectId Converter

Connect with

MongoDB objectId


In mongoDB, when you insert any document, by default _id field added by db engine while inserting if not peresent in the document. And one interesting things is, the value of _id consist of timestamp too, means its unique key generated by mongoDB engine. _id have much more that than timepstamp 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, 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 value of _id on bhalf 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.

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 Reply

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