1

In pymongo you can do something like this to create an OID from time:

dummy_id = ObjectId.from_datetime(time)

Is there something like that in mongoc?

I saw that there's a "bson_oid_get_time_t()" function, but is there a reverse function of this, and if not, How can it be implemented in C?

cydan
  • 615
  • 5
  • 17

1 Answers1

1

I don't believe there is a reverse function, but it should be easy for you to generate your own using the default constructor and "fixing" the time.

Here is an example where I create an object ID.

Then I create a timestamp for December 25, 2014 and modify the OID to that date.

#include <time.h>
#include <bson.h>

int
main (int   argc,
      char *argv[])
{
    time_t oid_thinks_time;  //what time does the OID think it is


    bson_oid_t oid;
    bson_oid_t *oid_pointer = &oid;
    bson_oid_init (&oid, NULL);  // get a standard ObjectId
    oid_thinks_time = bson_oid_get_time_t (&oid); //It was just made
    printf ("The OID was generated at %u\n", (unsigned) oid_thinks_time); //prove it



    time_t  ts = time(NULL);  //make a new time
    struct tm * timeinfo = localtime(&ts);
    timeinfo->tm_year = 2014-1900;  //-1900 because time.h
    timeinfo->tm_mon  = 12 - 1;     // time.h off by one (starts at 0)
    timeinfo->tm_mday = 25;
    ts = mktime(timeinfo);          // create the time
    u_int32_t ts_uint = (uint32_t)ts;
    ts_uint = BSON_UINT32_TO_BE (ts_uint); //BSON wants big endian time
    memcpy (&oid_pointer->bytes[0], &ts_uint, sizeof (ts_uint));  //overwrite the first 4 bytes with user selected time
    oid_thinks_time = bson_oid_get_time_t (&oid);
    printf ("The OID was fixed to time %u\n", (unsigned) oid_thinks_time);//prove it
}

The output of this code is:

The OID was generated at 1491238015
The OID was fixed to time 1419526015
bauman.space
  • 1,993
  • 13
  • 15