Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need created_at in MongoDB

Tags:

mongodb

Why do we when the created_at field when the timestamp can be found in the first 4 bytes of the ObjectId

ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()

Taken from MongoDB Docs

like image 614
Eduard Avatar asked Jan 03 '16 08:01

Eduard


Video Answer


2 Answers

There are several cases where it makes sense to do so:

  1. When you need better precision - ObjectId.getTimestamp() is precise up to seconds, while Date fields store milliseconds. Compare this in mongo shell: new Date() yields ISODate("2016-01-03T21:21:38.032Z"), while ObjectId().getTimestamp() yields ISODate("2016-01-03T21:21:50Z").

  2. When you are not using ObjectId at all - it is often taken as a given that _id field should be populated with ObjectId, while in fact ObjectId is only a default used by most of the drivers and MongoDB itself doesn't impose it - on the contrary, it is encouraged to use any "natural" unique ID if it exists for the documents. In this case though you will have to store "creation timestamp" yourself if you need it.

  3. Usability - if you rely on the presence of this field and the data in it, it might be better, at least from design standpoint, to be explicit about it. This is more a matter of taste though. However, as noted in comments, if you also want to filter or sort by "creation timestamp" - it will be easier to do having a dedicated field for it and using query operators like $gt, for example, directly on it.

like image 133
Timur Avatar answered Oct 27 '22 08:10

Timur


As you said, like it states clearly in the documentation:

Since the _id ObjectId by default stores the 4 byte timestamp, in most cases you do not need to store the creation time of any document.

And you may use ObjectId("5349b4ddd2781d08c09890f4").getTimestamp() in order to get the creation date in ISO date format.

It is also a matter of convenience to the costumer (us) to have a service like that, as it makes our attempt of getting the creating date and performing actions on it much more intuitive and easy.

like image 6
Idos Avatar answered Oct 27 '22 08:10

Idos