从 mongodb 的 id 中获取时间
2025-01-22 08:19:30    221 字   
This post is also available in English and alternative languages.

The automatically generated _id (ObjectId) field in MongoDB stores date information. The timestamp is contained within the first 4 bytes of the _id.

The _id (ObjectId) is a 12-byte BSON data, divided into four parts, where:

  1. The first 4 bytes represent the timestamp.
  2. The next 3 bytes are the machine identifier.
  3. The subsequent two bytes consist of the process id (PID).
  4. The last three bytes are randomly generated by the incremental counter.
mongodb _id

1
2
3
4
// ...
org.bson.types.ObjectId objectId = new org.bson.types.ObjectId(infoData.getId());
java.util.Date createTime = objectId.getDate();
// ...



↓↓↓↓↓ 中文 ↓↓↓↓↓

MongoDB 自动生成的 _id(ObjectId) 字段存储了日期的信息。时间戳包含在 _id 的前4个字节中。

_id(ObjectId) 是一个12个字节的BSON数据,分成四个部分,其中:

  1. 前4个字节表示时间戳;
  2. 接下来的3个字节是机器标识码;
  3. 紧接的两个字节由进程id组成(PID);
  4. 最后三个字节是自增计数器生成的随机数;
mongodb _id

1
2
3
4
// ...
org.bson.types.ObjectId objectId = new org.bson.types.ObjectId(infoData.getId());
java.util.Date createTime = objectId.getDate();
// ...