"""Offline MongoDB 12-byte BSON ObjectId encoder, decoder & timestamp verifier."""
from datetime import datetime, timezone
import json
import struct
VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
def encode_objectid(timestamp_sec, rand5_bytes, counter_24bit):
if len(rand5_bytes) != 5:
raise ValueError("rand5_bytes must be exactly 5 bytes")
if not (0 <= counter_24bit < (1 << 24)):
raise ValueError("counter must fit in 3 unsigned bytes")
raw = struct.pack(">I", timestamp_sec) + rand5_bytes + counter_24bit.to_bytes(3, "big")
return raw.hex()
def decode_objectid(hex_str):
raw = bytes.fromhex(hex_str)
if len(raw) != 12:
raise ValueError("ObjectId must be 12 bytes (24 hex chars)")
ts = struct.unpack(">I", raw[:4])[0]
machine_3b = raw[4:7].hex()
pid_2b = int.from_bytes(raw[7:9], "big")
rand5 = raw[4:9].hex()
counter = int.from_bytes(raw[9:12], "big")
iso_utc = datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
return {
"byte_length": len(raw),
"hex_length": len(hex_str),
"timestamp_sec": ts,
"iso_utc": iso_utc,
"legacy_machine_hex": machine_3b,
"legacy_pid": pid_2b,
"spec_v2_rand5_hex": rand5,
"counter": counter,
}
def main():
# Fixed deterministic inputs matching classic 2014-04-12T21:49:17Z ObjectId example
fixed_ts = 0x5349B4DD # 1397339357 -> 2014-04-12T21:49:17Z
fixed_rand5 = bytes.fromhex("d2781d08c0")
oid1 = encode_objectid(fixed_ts, fixed_rand5, 0x9890F3)
oid2 = encode_objectid(fixed_ts, fixed_rand5, 0x9890F4)
# Case 1: Deterministic 12-byte / 24-hex ObjectId generation & monotonic counter increment
c1_actual = {
"oid1": oid1,
"oid2": oid2,
"oid1_len": len(oid1),
"oid2_gt_oid1": oid2 > oid1,
}
c1_expected = {
"oid1": "5349b4ddd2781d08c09890f3",
"oid2": "5349b4ddd2781d08c09890f4",
"oid1_len": 24,
"oid2_gt_oid1": True,
}
# Case 2: Decode 4-byte timestamp (getTimestamp()), 5-byte random (legacy 3B machine + 2B PID), 3-byte counter
dec = decode_objectid(oid2)
c2_actual = dec
c2_expected = {
"byte_length": 12,
"hex_length": 24,
"timestamp_sec": 1397339357,
"iso_utc": "2014-04-12T21:49:17Z",
"legacy_machine_hex": "d2781d",
"legacy_pid": 2240,
"spec_v2_rand5_hex": "d2781d08c0",
"counter": 9998580,
}
# Case 3: String conversion (.str / .toHexString()) round-trip & 24-bit counter wraparound
wrapped = encode_objectid(fixed_ts, fixed_rand5, (0xFFFFFF + 1) & 0xFFFFFF)
c3_actual = {
"str_roundtrip": bytes.fromhex(oid1).hex() == oid1,
"wrapped_counter": decode_objectid(wrapped)["counter"],
}
c3_expected = {
"str_roundtrip": True,
"wrapped_counter": 0,
}
cases = [
{
"name": "objectid_12byte_encoding_and_ordering",
"summary": "Verify deterministic 12-byte (24-hex) ObjectId construction and monotonic counter increment.",
"expected": c1_expected,
"actual": c1_actual,
"passed": c1_actual == c1_expected,
},
{
"name": "objectid_timestamp_and_field_decoding",
"summary": "Verify 4-byte big-endian timestamp decoding matches 2014-04-12T21:49:17Z alongside 5-byte random and 3-byte counter.",
"expected": c2_expected,
"actual": c2_actual,
"passed": c2_actual == c2_expected,
},
{
"name": "objectid_hex_string_and_wraparound",
"summary": "Verify 24-hex string conversion round-trip and 24-bit counter modulo wraparound.",
"expected": c3_expected,
"actual": c3_actual,
"passed": c3_actual == c3_expected,
},
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。
入口文件:projects/mongodb-objectid-lab/explore-objectid.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-objectid.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1757.zip