【问题标题】:Can I get greater granularity out of a MongoDB timestamp?我可以从 MongoDB 时间戳中获得更大的粒度吗?
【发布时间】:2013-06-06 20:28:57
【问题描述】:

我从我的 MongoDB 数据库中获取了一个时间戳,但它只在几秒钟内准确返回:

2013 年 6 月 6 日星期四 16:15:22 GMT-0400(东部夏令时间)

我需要更大的粒度。有没有办法以毫秒为单位获取 MongoDB 时间戳?

我正在通过 mongoose 在我的 node.js 服务器上进行调用:

var timestamp = new ObjectID().getTimestamp();

我怎样才能得到更精确的东西?

【问题讨论】:

    标签: mongodb timestamp mongoose precision milliseconds


    【解决方案1】:

    ObjectId 以秒为精度存储,您无法更改它。因此,如果您需要毫秒粒度的东西,那么您必须存储自己的时间戳值。

    【讨论】:

    • 这很不幸。我使用 Mongo 时间戳的原因是我认为我的节点主机在两台不同的机器上运行我的服务器,这意味着一个请求中的 Date.now() 实际上可能比下一个请求中的时间更长。 Mongo 是一种集中时间的方式。是否有另一个集中式来源,我可以获得毫秒精度的时间,不会因可能有两个不同的节点服务器而受到影响?
    • 我使用不同的方式从 mongod 进程中获得相同的结果。私有日期 getDBTime() { return (Date)db.eval("function(){ return new Date()}"); }
    • 当为新文档生成 ObjectId() 时,生成它的是 CLIENT(即驱动程序),而不是服务器。
    • @MikePateras : 对其执行 getTime() ,它将以毫秒精度打印。
    • db.eval("return Date().getTime();", done);像那样?仍然只有几秒钟。 @AsyKamasky您是说我要取回节点服务器的时间,而不是数据库的时间吗?我没有注意到使用 Mongo 时间戳的任何时间问题,但我肯定使用了服务器的系统时间。
    【解决方案2】:

    我一个接一个地生成时间戳,得到了这些:

    ObjectId("586a291570b9a181fc2f61ba").getTimestamp();
    ISODate("2017-01-02T10:19:01Z")
    

    对于下一个时间戳:

    ObjectId("586a291570b9a181fc2f61bc").getTimestamp();
    ISODate("2017-01-02T10:19:01Z") 
    

    您会注意到,尽管getTimestamp() 打印的唯一粒度是以秒为单位,但还有一个更进一步的粒度会导致 ObjectId 字符串发生变化,即使它们都在 01 秒。

    The reason

    BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. Timestamp values are a 64 bit value where:
    
        the first 32 bits are a time_t value (seconds since the Unix epoch)
        the second 32 bits are an incrementing ordinal for operations within a given second.
    
    Within a single mongod instance, timestamp values are always unique.  
    

    所以真正的粒度是 MongoDB 生成的 32 位序数。它与operations within a second 相关,与时间值无关,因此您无法以毫秒为单位。

    【讨论】:

      猜你喜欢
      • 2018-08-20
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 2014-08-14
      • 2015-08-31
      相关资源
      最近更新 更多