How to Insert Documents with Custom ID in MongoDB
To insert a document with a custom
_id in MongoDB, include the _id field with your desired value in the document object when using insertOne() or insertMany(). MongoDB will use this value as the unique identifier instead of generating one automatically.Syntax
When inserting a document with a custom ID, you add the _id field explicitly in the document. The _id field can be any unique value like a string, number, or ObjectId.
db.collection.insertOne({ _id: customId, ...otherFields }): Inserts one document with a custom ID.db.collection.insertMany([{ _id: customId1, ... }, { _id: customId2, ... }]): Inserts multiple documents each with their own custom IDs.
mongodb
db.collection.insertOne({ _id: "custom123", name: "Alice", age: 30 })Example
This example shows how to insert a document with a custom string ID and then retrieve it.
mongodb
use testdb // Insert a document with custom _id db.users.insertOne({ _id: "user001", name: "John Doe", email: "john@example.com" }) // Find the document by custom _id db.users.find({ _id: "user001" }).pretty()
Output
{
"_id" : "user001",
"name" : "John Doe",
"email" : "john@example.com"
}
Common Pitfalls
Common mistakes when inserting with custom IDs include:
- Not providing the
_idfield, which causes MongoDB to generate one automatically. - Using duplicate
_idvalues, which causes a duplicate key error. - Using an unsupported data type for
_id(it must be a BSON type).
Always ensure your custom _id is unique and valid.
mongodb
/* Wrong: Duplicate _id causes error */ db.users.insertOne({ _id: "user001", name: "Jane" }) db.users.insertOne({ _id: "user001", name: "Jake" }) // Error: duplicate key /* Right: Use unique _id values */ db.users.insertOne({ _id: "user002", name: "Jake" })
Quick Reference
| Action | Syntax Example | Notes |
|---|---|---|
| Insert one with custom ID | db.collection.insertOne({ _id: "id123", field: value }) | Custom _id replaces auto-generated ObjectId |
| Insert many with custom IDs | db.collection.insertMany([{ _id: 1 }, { _id: 2 }]) | Each document needs a unique _id |
| Find by custom ID | db.collection.find({ _id: "id123" }) | Retrieve document using custom _id |
| Duplicate _id error | Inserting document with existing _id | Causes duplicate key error |
Key Takeaways
Include the _id field with your custom value when inserting documents to set a custom ID.
Ensure each custom _id is unique to avoid duplicate key errors.
The _id field can be any BSON type, not just ObjectId.
MongoDB uses your custom _id as the document's unique identifier instead of generating one.
Use insertOne or insertMany with documents containing _id to insert with custom IDs.