Convert a string to ObjectId in MongoDB (Node.js, Python, Java, C#)
Codemia Knowledge Hub ·
To convert a string to an ObjectID in MongoDB, pass it to the ObjectID constructor from your language's MongoDB driver. You need this whenever an _id arrives as a string (from user input or an external system) and you want to use it in lookups, references or aggregations.
What an ObjectID contains
An ObjectID is the unique identifier MongoDB generates by default for each document and uses as its primary key. It is a 12-byte value made of:
- 4 bytes for the timestamp, representing the ObjectID's time of creation.
- 5 bytes for a random value unique to the machine and process.
- 3 bytes for an incremental counter, initialized to a random value.
Why the string must be converted
MongoDB stores _id fields as ObjectID objects, not strings. Querying with the raw string leads to failed lookups and mismatches, so convert it first.
Conversion examples by language
JavaScript (Node.js)
The Node.js MongoDB driver provides an ObjectId class (the old ObjectID alias was removed in driver v5):
Python
The Python pymongo driver uses bson to handle ObjectID:
Java
The Java MongoDB driver contains the ObjectId class:
C#
The MongoDB C#/.NET driver provides the ObjectId structure:
Handling invalid IDs
Most drivers throw an error or raise an exception if the string is not a valid 24-character hexadecimal value, so handle that case. In JavaScript:
You can also validate that the string is 24 hexadecimal characters before converting, which avoids unnecessary exceptions.
Quick reference
| Aspect | Details |
| Structure of ObjectID | 12-byte identifier: 4-byte timestamp, 5-byte random, 3-byte counter |
| Why Convert? | Enables lookups and query operations on _id fields |
| JavaScript | Use ObjectId class from mongodb module |
| Python | Use ObjectId from bson module in pymongo |
| Java | Use ObjectId class from org.bson.types library |
| C# | Use ObjectId struct from MongoDB.Bson namespace |
| Error Handling | Validate string format and handle exceptions/throw errors appropriately |
Converting a single string is cheap, but when you process large datasets, profile and optimize the queries that use the converted ObjectIDs.
Related reading
- Convert timestamp to date in MySQL query
- convert_tz returns null
- Convert Unix timestamp into human readable date using MySQL
- converting database from mysql to mongoDb
- Copy SQL Server data from one server to another on a schedule
- Copy table without copying data
- Copy values from one column to another in the same table
- Copy/duplicate database without using mysqldump
System design interview problems on this topic
- Design a Distributed OLTP Database: solution and walkthrough
- Design a Wide Column Database: solution and walkthrough
- Design a Key Value Store: solution and walkthrough
- Design a Web Cache: solution and walkthrough

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseSystem Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.