Latest web development tutorials

MongoDB ObjectId

In the first few chapters we have used MongoDB object Id (ObjectId).

In this section, we will look at the structure of the ObjectId.

ObjectId BSON is a 12-byte data type, has the following format:

  • The first four bytes timestamp
  • The next three bytes of machine code is
  • Immediately two bytes composed by the process id (PID)
  • The last three bytes of random numbers.

MongoDB documents stored there must be a "_id" key. The value of this key can be any type, the default is ObjectId object.

In one set inside each document has a unique "_id" value, to ensure the collection inside each document can be uniquely identified.

MongoDB uses ObjectId, but not the main reason other more conventional approach (such as auto-increment primary key), because the primary key value is automatically increased synchronization across multiple servers is also time-consuming and laborious.


Create a new ObjectId

Use the following code to generate a new ObjectId:

>newObjectId = ObjectId()

The above statement returns the following uniquely generated id:

ObjectId("5349b4ddd2781d08c09890f3")

You can also use the generated id instead of MongoDB automatically generated ObjectId:

>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")

Creation timestamp documents

Since ObjectId stored in four bytes of the time stamp, so you do not need to save the timestamp field for your documents, you can create time to get the documents by getTimestamp function:

>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()

The above code will return the ISO format document creation time:

ISODate("2014-04-12T21:49:17Z")

ObjectId converted to a string

In some cases, you may need to convert a string ObjectId format. You can use the following code:

>new ObjectId().str

The above code will return the string Guid format ::

5349b4ddd2781d08c09890f3