0
0
MongoDBquery~5 mins

Auto-generated _id behavior in MongoDB

Choose your learning style9 modes available
Introduction
MongoDB automatically creates a unique _id for each document to identify it easily without extra work.
When you insert a new document and don't provide an _id, MongoDB creates one for you.
When you want to ensure each document has a unique identifier without manually generating it.
When you want to quickly find or update a document by its unique _id.
When you want to avoid duplicate documents in a collection.
When you want to link documents using their unique _id values.
Syntax
MongoDB
db.collection.insertOne({ field1: value1, field2: value2 })
If you do not specify the _id field, MongoDB adds it automatically.
The auto-generated _id is an ObjectId, which is a 12-byte unique value.
Examples
Inserts a new user document. MongoDB creates a unique _id automatically.
MongoDB
db.users.insertOne({ name: "Alice", age: 30 })
Inserts a user with a custom _id instead of auto-generated one.
MongoDB
db.users.insertOne({ _id: "customID123", name: "Bob" })
Finds a document by its auto-generated ObjectId _id.
MongoDB
db.users.findOne({ _id: ObjectId("507f1f77bcf86cd799439011") })
Sample Program
This inserts a product without specifying _id. MongoDB creates a unique _id automatically. Then it finds and shows the inserted document using that _id.
MongoDB
use testdb

// Insert a document without _id
var result = db.products.insertOne({ name: "Pen", price: 1.5 })

// Show the inserted document with auto-generated _id
var doc = db.products.findOne({ _id: result.insertedId })
doc
OutputSuccess
Important Notes
The ObjectId contains a timestamp, machine id, process id, and a counter to ensure uniqueness.
You can provide your own _id, but it must be unique in the collection.
Trying to insert a document with a duplicate _id will cause an error.
Summary
MongoDB auto-generates a unique _id for each document if you don't provide one.
The _id is an ObjectId by default, which helps uniquely identify documents.
You can use the _id to quickly find, update, or delete documents.