I've been reading about MongoDB using timestamps of object's creation to create ids. Is it valid to simply compare these and find out which object's been created earlier?
2 Answers
You can compare ObjectIDs with the .equals()
. See the documentation.
ObjectId is a hexadecimal string which represents a 12-byte number.
- a 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch
- a 5-byte random value
- a 3-byte incrementing counter, initialized to a random value
Since the time stamp is the most significant part of an ObjectId, yes you can. Selecting the most significant four bytes of the ObjectId as the time stamp.
Also see ObjectId.getTimestamp()
documentation.

- 1,945
- 1
- 6
- 26
-
This answer's example of using .equals() has a reference to nodeJS documentation. While this answer is entirely accurate there are some language differences. For example, python can use the == operator. – barrypicker Jun 26 '21 at 22:35
generally, it is possible to compare Objects' creation by ObjectId: for more info, refer this link.
-- citing this link: https://steveridout.github.io/
Why generate an ObjectId from a timestamp? To query documents by creation date.
e.g. to find all comments created after 2013-11-01:
db.comments.find({_id: {$gt: ObjectId("5272e0f00000000000000000")}})
-- another helpful and explanatory link: uses for mongodb ObjectId creation time
best regards

- 11
- 3