我怎样才能从时间创建一个OID

How can I create an OID from time

在 pymongo 中你可以像这样从时间创建一个 OID:

dummy_id = ObjectId.from_datetime(time)

mongoc 中有类似的东西吗?

我看到有一个“bson_oid_get_time_t()”的函数,请问有没有这个的逆向函数,如果没有,如何实现C?

我不相信有反向函数,但您使用默认构造函数和 "fixing" 时间应该很容易生成您自己的函数。

这是我创建对象 ID 的示例。

然后我为 2014 年 12 月 25 日创建时间戳并将 OID 修改为该日期。

#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 OID was generated at 1491238015
The OID was fixed to time 1419526015