MongoDB_id(ObjectId)是按升序生成的吗?

Is MongoDB _id (ObjectId) generated in an ascending order?

我知道当文档被插入到集合中时,_id 列如何包含时间戳的表示。这是一个将其转换为时间戳的在线实用程序:http://steveridout.github.io/mongo-object-time/

我想知道对象id字符串本身是否保证保持升序?也就是说,这种比较总是 return 正确吗?

"newest object id" > "second newest object id"

不,没有任何保证。来自 official documentation (at the time of the original answer):

The relationship between the order of ObjectId values and generation time is not strict within a single second. If multiple systems, or multiple processes or threads on a single system generate values, within a single second; ObjectId values do not represent a strict insertion order. Clock skew between clients can also result in non-strict ordering even for values, because client drivers generate ObjectId values, not the mongod process.

并且来自 latest docs

While ObjectId values should increase over time, they are not necessarily monotonic. This is because they:

Only contain one second of temporal resolution, so ObjectId values created within the same second do not have a guaranteed ordering, and Are generated by clients, which may have differing system clocks.

_id: ObjectId(4字节时间戳,3字节机器id,2字节进程id,3字节增量)

这是id结构。所以只有最后 3 个字节会唯一递增。所以你的问题的答案是肯定的。

对于mongo version >= 3.4,Objectid的生成稍有改动。 它的结构是:

  • 一个 4 字节的值,表示自 Unix 纪元以来的秒数,
  • 一个 5 字节的随机值,并且
  • 一个 3 字节的计数器,以随机值开头。

所以前 4 个字节仍然是自 Unix 纪元以来的秒数,它仍然几乎是递增的,但不是严格的。

https://docs.mongodb.com/manual/reference/bson-types/#objectid