In MongoDB you can retrieve the date from an ObjectId using the getTimestamp()
function. How can I retrieve the date from a MongoDB ObjectId using SQL (e.g., in the case where such an ObjectId is stored in a MySQL database)?
Example input:
507c7f79bcf86cd7994f6c0e
Wanted output:
2012-10-15T21:26:17Z
An ObjectId is a 12-byte BSON type having the following structure − The first 4 bytes representing the seconds since the unix epoch. The next 3 bytes are the machine identifier. The next 2 bytes consists of process id. The last 3 bytes are a random counter value.
No. Since ObjectIDs are typically generated on the client, the deployment topology does not factor into the ordering of ObjectIDs. Even if the ObjectIDs are generated on the server, multiple ObjectIDs generated in the same second will not have a predictable ordering.
ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.
This can be achieved as follows (assuming objectId
is a string) in MySQL:
SELECT FROM_UNIXTIME(
CAST(CONV(SUBSTR(objectId, 1, 8), 16, 10) AS UNSIGNED)
) FROM table
It works as follows:
SUBSTR(objectId, 1, 8)
takes the first 8 characters from the hexadecimal objectId
stringCONV(..., 16, 10)
converts the hexadecimal number into a decimal number and returns it as a string (which represents the UNIX timestamp)CAST (...) AS UNSIGNED
converts the timestamp string to an unsigned integerFROM_UNIXTIME(...)
converts the timestamp integer into the dateNote that by default the displayed date will be based on your system's timezone settings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With