ObjectId

Object ID is a unique identifier in MongoDB and one of its primary datatypes. It is the default identifier created by MongoDB when you insert a document into a collection without specifying an _id.

Structure of an Object ID

An Object ID consists of 12 bytes, where:

Benefits of Object ID

Working with Object ID

Here are a few examples of how to work with Object IDs in MongoDB:

1. Inserting a document without specifying an _id:

db.collection.insertOne({ title: 'Example' });

Output:

{
  "_id": ObjectId("60c4237a89293ddc1ef23245"),
  "title": "Example"
}

2. Creating Object ID manually:

const { ObjectId } = require('mongodb');
const objectId = new ObjectId();

3. Converting Object ID to a string:

const objectIdStr = objectId.toString();

4. Converting a string back to an Object ID:

const objectIdFromStr = ObjectId(objectIdStr);

Conclusion

The Object ID datatype in MongoDB is a very powerful and efficient way to uniquely identify documents in a collection. Its structure provides valuable information about the document’s creation, and its design ensures high performance and scalability for large-scale MongoDB deployments. Understanding and effectively utilizing Object IDs is essential for successful MongoDB usage.