MongoDB
ObjectID
string conversion
database
NoSQL

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):

javascript
1const { ObjectId } = require('mongodb');
2
3// Convert string to ObjectID
4const strId = "507f1f77bcf86cd799439011";
5const objectId = new ObjectId(strId);
6
7console.log(objectId);

Python

The Python pymongo driver uses bson to handle ObjectID:

python
1from bson.objectid import ObjectId
2
3# Convert string to ObjectID
4str_id = "507f1f77bcf86cd799439011"
5object_id = ObjectId(str_id)
6
7print(object_id)

Java

The Java MongoDB driver contains the ObjectId class:

java
1import org.bson.types.ObjectId;
2
3// Convert string to ObjectID
4String strId = "507f1f77bcf86cd799439011";
5ObjectId objectId = new ObjectId(strId);
6
7System.out.println(objectId);

C#

The MongoDB C#/.NET driver provides the ObjectId structure:

csharp
1using MongoDB.Bson;
2
3// Convert string to ObjectID
4string strId = "507f1f77bcf86cd799439011";
5ObjectId objectId = new ObjectId(strId);
6
7Console.WriteLine(objectId);

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:

javascript
1const { ObjectId } = require('mongodb');
2
3try {
4  const strId = "InvalidID"; // Invalid format
5  const objectId = new ObjectId(strId);
6} catch (error) {
7  console.error("Conversion failed:", error.message);
8}

You can also validate that the string is 24 hexadecimal characters before converting, which avoids unnecessary exceptions.

Quick reference

AspectDetails
Structure of ObjectID12-byte identifier: 4-byte timestamp, 5-byte random, 3-byte counter
Why Convert?Enables lookups and query operations on _id fields
JavaScriptUse ObjectId class from mongodb module
PythonUse ObjectId from bson module in pymongo
JavaUse ObjectId class from org.bson.types library
C#Use ObjectId struct from MongoDB.Bson namespace
Error HandlingValidate 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.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design