0
0
MongoDBquery~5 mins

Custom _id values in MongoDB

Choose your learning style9 modes available
Introduction

Every document in MongoDB needs a unique _id. Using custom _id values lets you control this unique identifier instead of letting MongoDB create one automatically.

When you want to use meaningful IDs like usernames or email addresses as the document ID.
When you need to link documents across collections using a known ID.
When importing data from another system that already has unique IDs.
When you want to avoid the extra space of MongoDB's default ObjectId.
When you want to quickly find documents by a known key without extra indexing.
Syntax
MongoDB
db.collection.insertOne({ _id: customValue, otherField: value })

The _id field can be any unique value: string, number, or object.

If you don't provide _id, MongoDB creates a unique ObjectId automatically.

Examples
Insert a user with a string _id "user123".
MongoDB
db.users.insertOne({ _id: "user123", name: "Alice" })
Insert a product with a numeric _id 1001.
MongoDB
db.products.insertOne({ _id: 1001, name: "Pen", price: 1.5 })
Insert an order with a custom object as _id.
MongoDB
db.orders.insertOne({ _id: { orderNumber: 500, region: "US" }, total: 250 })
Sample Program

This example inserts a product with a custom string _id "sku123" and then finds it using that _id.

MongoDB
use shop

// Insert a product with custom _id
 db.products.insertOne({ _id: "sku123", name: "Notebook", price: 3.99 })

// Find the product by _id
 db.products.find({ _id: "sku123" })
OutputSuccess
Important Notes

Custom _id values must be unique in the collection; duplicates cause errors.

Using meaningful _id values can make queries faster since _id is always indexed.

Summary

Every MongoDB document needs a unique _id.

You can set your own _id value instead of using the default ObjectId.

Custom _id helps with meaningful IDs and faster lookups.