Skip to content

Convert MongoDB ObjectId to timestamp and vice versa

Learn how to convert MongoIn any database, either Relational or NOSQL db, in a table/collection, there is a primary key for each row/document which is always unique. In MongoDB it’s ObjectId. ObjectId is a 12 byte value which consists of 4 bytes of creation time in seconds, 5 bytes of random value and 3 bytes of counter.

Check out our own MongoDB ObjectId to Timestamp Converter.

Advertisements

When you are working with mongo documents, sometimes you just want to create ObjectId from timestamps for querying through the collection. You can easily convert ObjectId to Timestamp and timestamp to ObjectId using the following code in JavaScript. Thanks to Steve Ridout, this looks so simple!

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

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

There’s another similar solution developed by Kumar Harsh.

Check out our own MongoDB ObjectId to Timestamp Converter.

See also  Dynamic key in MongoDB Node.js Native API
, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.