Mongo Timestamps & Object Ids

MongoDB uses an indexing system based on ObjectIds, which are formed of 12 bytes. They are unique within a MongoDB collection (as all indexes should be), and to ensure their uniqueness they use a combination of a timestamp, an incrementing counter and random numbers.

If you maintain the ObjectId as the document's index in the MongoDB collections (it's possible to remove it and use a different field for indexing), then, you have the timestamp information within those 12 bytes. More accurately, the first 4 bytes contain the timestamp of the creation of the document.

This is useful if you need to review when documents were inserted (the ObjectId will not change on document updates), or find all documents created within a time period.

// Get all documents created after 2020
db.records.find({
  _id: { $gt: ObjectId("5e0bd2f00000000000000000") }
})

The useful part is that the timestamp is directly stored in the 4 most significant bytes of the ObjectId, so, the rest of the identifier can be set to zero, and, it's easy to use in a query (as shown above). Here's a small tool to convert dates to MongoDB's ObjectId format!

You can change the ObjectId to see the correspnding date or, modify any of the date values to see the equivalent ObjectId! The date values can't go earliear than 1970, since this is when the Unix timestamp starts counting!

More concepts