Is it possible to retroactively add "createdAt" key in each document of a mongoDB collection

120 Views Asked by At

I only recently thought it was a good idea to add createdAt as a default field in our User collection in mongoDB. Unfortunately, for all users that have signed up previously, this createdAt field is missing.

enter image description here

I feel like I am probably out of luck, but I wonder if perhaps the createdAt is either somehow encoded in the _id, or is available as metadata somewhere, anywhere. Is this possible?

As an aside, I have all of the email verification emails sent from our gmail account that are sent when a user signs up / gets added to this collection. It's a stretch, but maybe there's an automated way to extract all of those email send times, and use the email field to join those email send times onto our User collection.

1

There are 1 best solutions below

0
YuTing On

MongoDB 12-byte ObjectId value consists of:

  • 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch.
  • 5-byte random value generated once per process. This random value is unique to the machine and process.
  • 3-byte incrementing counter, initialized to a random value.

For example:

ObjectId("61e52e26fd6b5909358c902a")

61e52e26 (hexadecimal) => 1642409510 (decimal) => 2022/1/17 08:51:50

So you can use _id as createdAt