ObjectId

On this page本页内容

Description描述

ObjectId(<hexadecimal>)

Returns a new ObjectId value. 返回新的ObjectId值。The 12-byte ObjectId value consists of:12字节的ObjectId值包括:

  • a 4-byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch一个4字节的时间戳值,表示ObjectId的创建,自Unix时代以来以秒为单位
  • a 5-byte random value5字节的随机值
  • a 3-byte incrementing counter, initialized to a random value3字节递增计数器,初始化为随机值

While the BSON format itself is little-endian, the timestamp and counter values are big-endian, with the most significant bytes appearing first in the byte sequence.虽然BSON格式本身是小端的,但时间戳计数器值是大端的,最重要的字节出现在字节序列的第一位。

ObjectId() can accept the following parameter:可以接受以下参数:

Field字段Type类型Description描述
hexadecimal String字符串 Optional.可选。Hexadecimal string value for the new ObjectId.新ObjectId的十六进制字符串值。

Methods and Attributes方法和属性

ObjectId() has the following attribute and methods:具有以下属性和方法:

Attribute/Method属性/方法Description描述
str Returns the hexadecimal string representation of the object.返回对象的十六进制字符串表示形式。
ObjectId.getTimestamp() Returns the timestamp portion of the object as a Date.返回对象的时间戳部分作为日期。
ObjectId.toString() Returns the JavaScript representation in the form of a string literal “ObjectId(...)”.以字符串文字"ObjectId(...)"的形式返回JavaScript表示。
ObjectId.valueOf() Returns the representation of the object as a hexadecimal string. 返回对象的十六进制字符串表示形式。The returned string is the str attribute.返回的字符串是str属性。

Examples示例

Generate a New ObjectId生成新的ObjectId

To generate a new ObjectId, use ObjectId() with no argument:要生成新的ObjectId,请使用不带参数的ObjectId()

x = ObjectId()

In this example, the value of x would be:在本例中,x的值为:

ObjectId("507f1f77bcf86cd799439011")

Specify a Hexadecimal String指定十六进制字符串

To generate a new ObjectId using ObjectId() with a unique hexadecimal string:要使用具有唯一十六进制字符串的ObjectId()生成新的ObjectId,请执行以下操作:

y = ObjectId("507f191e810c19729de860ea")

In this example, the value of y would be:在本例中,y的值为:

ObjectId("507f191e810c19729de860ea")

Access the Hexadecimal String访问十六进制字符串

Access the str attribute of an ObjectId() object, as follows:访问ObjectId()对象的str属性,如下所示:

ObjectId("507f191e810c19729de860ea").str

This operation will return the following hexadecimal string:此操作将返回以下十六进制字符串:

507f191e810c19729de860ea

See also参阅

ObjectId BSON Type