1

我正在尝试将 UTC 时间戳直接插入我的 $push 命令(如下)。我想在当前显示“UTC TIME HERE PLEASE”的地方获取 UTC 字符串。

update = BCON_NEW ("$push", 
      "{", 
        "folder.0.files", 
            "{", 
                "file",     BCON_UTF8 (file_id), 
                "modified", BCON_UTF8 ("UTC TIME HERE PLEASE"), 
            "}", 
    "}");

不同的方式,在这里不起作用

我知道如何将 UTC 字符串附加到命令列表(见下文),但该结构在我尝试执行的 $push 的上下文中不起作用。

update = bson_new ();
bson_append_now_utc(update, "time", -1);
mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);

有什么建议么?

谢谢


更新

感谢 Totonga,我将代码调整为:

// Current time
long            ms; // Milliseconds
time_t          s;  // Seconds
struct timespec spec;

clock_gettime(CLOCK_REALTIME, &spec);

s  = spec.tv_sec;
ms = round(spec.tv_nsec / 1.0e6); // Convert nanoseconds to milliseconds

// Update Mongo
update = BCON_NEW ("$push", 
    "{", 
        "folder.0.files", 
            "{", 
                "file",     BCON_UTF8 (file_id),
                "modified", BCON_DATE_TIME (ms), 
            "}", 
    "}");

这在 Mongo 中给了我一个 ISODate,但它显示了错误的日期值:

"modified" : ISODate("1970-01-01T00:00:00.913+0000")


使用工作代码的最终更新 使用这篇文章中的一些代码和 Totonga 的建议,我能够获得工作代码:

// Current time
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long long millisecondsSinceEpoch =
(unsigned long long)(tv.tv_sec) * 1000 +
(unsigned long long)(tv.tv_usec) / 1000;

// add new file
update = BCON_NEW ("$push", 
    "{", 
        "folder.0.files", 
            "{", 
                "file",     BCON_UTF8 (file_id), 
                "modified", BCON_DATE_TIME (millisecondsSinceEpoch), 
            "}", 
    "}");

mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);
4

1 回答 1

1

使用这篇文章中的一些代码和 Totonga 的建议,我能够获得工作代码:

// Current time
struct timeval tv;
gettimeofday(&tv, NULL);
unsigned long long millisecondsSinceEpoch =
(unsigned long long)(tv.tv_sec) * 1000 +
(unsigned long long)(tv.tv_usec) / 1000;

// add new file
update = BCON_NEW ("$push", 
    "{", 
        "folder.0", 
            "{", 
                "file",     BCON_UTF8 (file_id), 
                "modified", BCON_DATE_TIME (millisecondsSinceEpoch), 
            "}", 
    "}");

mongoc_collection_update (collection, MONGOC_UPDATE_NONE, query, update, NULL, &error);
于 2015-11-13T12:58:25.327 回答