Create ObjectId in MongoDB using a seed string?

MongoDB's ObjectId cannot directly accept a seed string, but you can create custom _id values using string identifiers instead of the default ObjectId format. This approach gives you control over document identification while maintaining uniqueness.

Syntax

db.collection.insertOne({_id: "stringValue"});

Create Sample Data

Insert documents with custom string-based _id values ?

db.demo667.insertMany([
    {_id: "Chris"},
    {_id: "David"},
    {_id: "Bob"},
    {_id: "Mike"}
]);
{
  "acknowledged": true,
  "insertedIds": ["Chris", "David", "Bob", "Mike"]
}

Example: Duplicate Key Error

Attempting to insert a duplicate _id will result in an error ?

db.demo667.insertOne({_id: "Chris"});
WriteError: E11000 duplicate key error collection: test.demo667 index: _id_ dup key: { : "Chris" }

Verify Results

Display all documents to confirm the custom _id values ?

db.demo667.find();
{ "_id" : "Chris" }
{ "_id" : "David" }
{ "_id" : "Bob" }
{ "_id" : "Mike" }

Key Points

  • Custom string _id values must be unique within the collection.
  • MongoDB automatically creates a unique index on the _id field.
  • String-based _id values are sorted lexicographically, not chronologically like ObjectId.

Conclusion

While ObjectId doesn't support seed strings directly, you can use custom string values for _id fields. This provides human-readable identifiers but requires manual uniqueness management and loses ObjectId's built-in timestamp functionality.

Updated on: 2026-03-15T03:27:22+05:30

448 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements