【问题标题】:Mongo C Driver: Insert UTC Time directly into BCON $pushMongo C 驱动程序:将 UTC 时间直接插入 BCON $push
【发布时间】:2015-11-11 12:58:53
【问题描述】:

我正在尝试将 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")


带工作代码的最终更新 使用来自this post 的一些代码和 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);

【问题讨论】:

  • Should not it be BCON_DATE_TIME(ms) where time is given in ms.
  • @Totonga 请查看我的问题的更新,谢谢:)

标签: mongodb datetime gcc utc mongo-c-driver


【解决方案1】:

使用this post 的一些代码和 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);

【讨论】:

    猜你喜欢
    • 2018-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 2013-04-03
    • 1970-01-01
    相关资源
    最近更新 更多