Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve the date from a MongoDB ObjectId using SQL

Tags:

sql

mongodb

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
like image 518
Sicco Avatar asked Mar 17 '14 12:03

Sicco


People also ask

What is the ObjectId in MongoDB?

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.

Is MongoDB ObjectId ordered?

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.

How does MongoDB ObjectId work?

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.


1 Answers

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 string
  • CONV(..., 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 integer
  • FROM_UNIXTIME(...) converts the timestamp integer into the date

Note that by default the displayed date will be based on your system's timezone settings.

like image 146
Sicco Avatar answered Nov 01 '22 13:11

Sicco