Skip to content

MongoDB ObjectId

In MongoDB, ObjectId is a special type of field used to uniquely identify documents in a collection. ObjectId is automatically generated by MongoDB and has a specific structure and characteristics.

Basic Concepts

Structure of ObjectId

ObjectId is a 12-byte BSON type field composed of the following parts:

  1. Timestamp: The first 4 bytes represent the creation time of ObjectId.
  2. Machine Identifier: The next 3 bytes represent the identifier of the machine.
  3. Process Identifier: The next 2 bytes represent the identifier of the process.
  4. Counter: The last 3 bytes represent a counter used to ensure the uniqueness of ObjectId.

Characteristics of ObjectId

  1. Uniqueness: Each ObjectId is unique.
  2. Monotonicity: ObjectId is monotonically increasing.
  3. Compactness: ObjectId is only 12 bytes in size, more compact than UUID.
  4. Sortability: ObjectId can be sorted by timestamp.

Generating ObjectId

Automatically Generated by MongoDB

In MongoDB, when we insert a document, if we don't specify the _id field, MongoDB will automatically generate an ObjectId.

javascript
// When inserting a document, MongoDB automatically generates the _id field
db.users.insertOne({
  name: "John",
  age: 30,
  email: "john@example.com",
  status: "active"
})

Manually Generating

We can also manually generate ObjectId.

javascript
// Manually generate ObjectId
const ObjectId = require("mongodb").ObjectId
const id = new ObjectId()

console.log(id)

Querying ObjectId

Querying a Single Document

javascript
// Query a single document
db.users.findOne({ _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") })

Querying Multiple Documents

javascript
// Query multiple documents
db.users.find({
  _id: {
    $in: [
      ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f"),
      ObjectId("5e8f8f8f8f8f8f8f8f8f8f90"),
      ObjectId("5e8f8f8f8f8f8f8f8f8f8f91")
    ]
  }
})

Operations on ObjectId

Getting Creation Time

We can get the creation time of a document through ObjectId.

javascript
// Get the creation time of a document
const id = ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f")
const createdAt = id.getTimestamp()

console.log(createdAt)

Converting to String

We can convert ObjectId to a string.

javascript
// Convert ObjectId to string
const id = ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f")
const idStr = id.toString()

console.log(idStr)

Comparing ObjectId

We can compare the size of two ObjectId.

javascript
// Compare the size of two ObjectId
const id1 = ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f")
const id2 = ObjectId("5e8f8f8f8f8f8f8f8f8f8f90")

console.log(id1 < id2) // Output true
console.log(id1 > id2) // Output false

Best Practices for ObjectId

Use ObjectId Generated by MongoDB

In most cases, we should use ObjectId generated by MongoDB because it has characteristics such as uniqueness, monotonicity, and compactness.

Do Not Modify ObjectId

We should not modify ObjectId because it is the unique identifier of the document. If we modify ObjectId, it may cause consistency problems with the document.

Avoid Using ObjectId as a Business Primary Key

Although ObjectId can be used as a unique identifier for documents, we should not use it as a business primary key because its structure and characteristics are not suitable for business primary keys.

Summary

In MongoDB, ObjectId is a special type of field used to uniquely identify documents in a collection. ObjectId is composed of a timestamp, machine identifier, process identifier, and counter, and has characteristics such as uniqueness, monotonicity, and compactness. In most cases, we should use ObjectId generated by MongoDB because it has good characteristics. At the same time, we should also avoid modifying ObjectId and using it as a business primary key.

Content is for learning and research only.