Stop using `created_at` with MongoDB

Eslam Shoaala
2 min readApr 30, 2018

Keeping track of when was your document created in your database is important for sure. But why should you explicitly add an extra field in your database when already MongoDB provides you with it?

MongoDB has this magical ObjectID. ObjectID is the unique identifier for your Mongo Documents. And it has some magic within.

ObjectID is not an auto-increment integer, rather it uses a randomly generated ID. This is quite good with scaling as when distributing your database instances on different machines, they do not need to keep track of the highest/last inserted ID and increment that by one. Let’s have a closer look on what the ObjectID consists of…

ObjectID consists of 12 bytes. The first four are reserved for a time stamp in which the document was created. In other words, the ‘created_at’ field is already encoded in your automatically generated ID. The next three bytes are machine identifiers, which is used to differentiate two machines writing different documents to the database to ensure the generation of different IDs to avoid clashes. Then the remaining 3 bytes are a counter which is randomly generated.

For demo; let’s create a dummy object and print out its created_at date

//JAVASCRIPT
db.collection('Products').insertOne({
name: 'iPhone X',
trademark: 'Apple'
}, (err, result) => {
if (err) return console.log(err);

console.log(result.op[0]._id.getTimeStamp());
});

You should be able to see the TimeStamp printed in your console.

Happy coding! ☕️

--

--

Eslam Shoaala

Software Engineer 👨‍💻 | Full-time learner 📚