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:
- Timestamp: The first 4 bytes represent the creation time of ObjectId.
- Machine Identifier: The next 3 bytes represent the identifier of the machine.
- Process Identifier: The next 2 bytes represent the identifier of the process.
- Counter: The last 3 bytes represent a counter used to ensure the uniqueness of ObjectId.
Characteristics of ObjectId
- Uniqueness: Each ObjectId is unique.
- Monotonicity: ObjectId is monotonically increasing.
- Compactness: ObjectId is only 12 bytes in size, more compact than UUID.
- 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.
// 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.
// Manually generate ObjectId
const ObjectId = require("mongodb").ObjectId
const id = new ObjectId()
console.log(id)Querying ObjectId
Querying a Single Document
// Query a single document
db.users.findOne({ _id: ObjectId("5e8f8f8f8f8f8f8f8f8f8f8f") })Querying Multiple Documents
// 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.
// 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.
// 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.
// 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 falseBest 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.