ObjectId()
Descrição
ObjectId(<value>)
Importante
Método mongosh
Esta página documenta um método
mongosh
. Esta não é a documentação para um driver específico de idioma, como Node.js.Para drivers de API do MongoDB, consulte a documentação do driver do MongoDB específica da linguagem.
Returns a new ObjectId. The 12-byte ObjectId consists of:
Um carimbo de data/hora de bytes, representando a criação do ObjectID, medido em segundos desde a época do Unix.
Um valor aleatório de 5 bytes gerado uma vez por processo. Este valor aleatório é exclusivo da máquina e do processo.
Um contador incrementador de 3 bytes, inicializado para um valor aleatório.
Para valores de carimbo de data/hora e contador, os bytes mais significativos aparecem primeiro na sequência de bytes (big-endian). Isto é diferente de outros valores de BSON, onde os bytes menos significativos aparecem primeiro (little-endian).
Se um valor inteiro for usado para criar um ObjectId, o número inteiro substituirá o carimbo de data/hora.
Compatibilidade
Você pode utilizar o ObjectId()
para implantações hospedadas nos seguintes ambientes:
MongoDB Atlas: o serviço totalmente gerenciado para implantações do MongoDB na nuvem
MongoDB Enterprise: a versão autogerenciada e baseada em assinatura do MongoDB
MongoDB Community: uma versão com código disponível, de uso gratuito e autogerenciada do MongoDB
Sintaxe
ObjectId()
can accept one of the following inputs:
Tipo de entrada | Descrição |
---|---|
| Optional. A 24 character hexadecimal string value for the new ObjectId. |
| Optional. The integer value, in seconds, is added to the Unix epoch to create the new timestamp. |
Métodos
ObjectId()
has the following methods:
Métodos | Descrição |
---|---|
Returns the timestamp portion of the object as a Date. | |
Returns the ObjectId as a hexadecimal string. |
Comportamento
A partir do MongoDB 5.0, mongosh
substitui o shell legado mongo
. Os métodos ObjectId()
funcionam de maneira diferente em mongosh
e no shell mongo
herdado. Para obter mais informações sobre os métodos legados, consulte Legacy mongo Shell.
Exemplos
Generate a New ObjectId
To generate a new ObjectId, use ObjectId()
with no argument:
newObjectId = ObjectId()
In this example, the value of newObjectId
is:
ObjectId("507f1f77bcf86cd799439011")
Return a Hexadecimal String
To return the ObjectId as a hexadecimal string, use the toString()
method.
ObjectId("507f191e810c19729de860ea").toString()
The method returns:
507f191e810c19729de860ea
Specify a Date
You can use a custom Data to specify an ObjectId.
Set a variable for your specified date
Internally, Date objects are stored as signed
64-bit integer that represents the number of milliseconds since the
Unix epoch. To learn more, see Date()
.
myDate = new Date( "2024-01-01" )
Set your new ObjectId with timestamp
as the argument
You can verify the Date by using ObjectId.getTimestamp()
.
newObjectId = ObjectId(timestamp)
ObjectId("6592008029c8c3e4dc76256c")
Specify an Integer String
If you want to adjust the ObjectId timestamp, use an integer to generate a new ObjectId.
newObjectId = ObjectId(32)
The ObjectId value resembles:
ObjectId("00000020f51bb4362eee2a4d")
The example ObjectId consists of:
A four byte time stamp,
00000020
A five byte random element,
f51bb4362e
A three byte counter,
ee2a4d
The first four bytes of the ObjectId are the number of seconds since the
Unix epoch. In this example, the ObjectId timestamp is
00000020
which is 32
in hexadecimal.
Specify a Hexadecimal String
If you want to use a hexadecimal string to specify an ObjectId, pass a
unique, 24 character hexadecimal value when you call
ObjectId()
:
newObjectId = ObjectId("507f191e810c19729de860ea")