官方對 ObjectId 的描述:https://docs.mongodb.com/manual/reference/method/ObjectId/#objectid
- a 4-byte timestamp value, representing the ObjectId's creation, measured in seconds since the Unix epoch
- a 5-byte random value
- a 3-byte incrementing counter, initialized to a random value
Golang 使用的客戶端為 https://github.com/mongodb/mongo-go-driver ,此文章使用的版本 v1.7.0
源碼為 go.mongodb.org/mongo-driver@v1.7.0/bson/primitive/objectid.go
func NewObjectID() ObjectID {
return NewObjectIDFromTimestamp(time.Now())
}
// NewObjectIDFromTimestamp generates a new ObjectID based on the given time.
func NewObjectIDFromTimestamp(timestamp time.Time) ObjectID {
var b [12]byte // 12個字節(jié)
binary.BigEndian.PutUint32(b[0:4], uint32(timestamp.Unix())) // 前4個字節(jié)為時間戳
copy(b[4:9], processUnique[:]) // "不變的"5字節(jié)隨機(jī)數(shù)
putUint24(b[9:12], atomic.AddUint32(&objectIDCounter, 1)) // 動態(tài)變化的"不變的"3字節(jié)隨機(jī)數(shù)+1
return b
}
隨機(jī)數(shù)就是預(yù)料之中的 /dev/urandom ,Go相關(guān)代碼為 go/src/crypto/rand/rand_unix.go