Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Cast to ObjectId failed for value in MongoDB?
The "Cast to ObjectId failed" error occurs when MongoDB cannot convert a string value to a valid ObjectId. This happens when the string is not a valid 24-character hexadecimal ObjectId format. Use the $toObjectId operator in aggregation pipelines to safely convert string values to ObjectId.
Syntax
db.collection.aggregate([
{
$addFields: {
"newField": { $toObjectId: "$stringField" }
}
}
]);
Sample Data
Let us create a collection with a string _id that we want to convert to ObjectId ?
db.demo460.insertOne({
"_id": "5ab9cbfa31c2ab715d42129e"
});
{
"acknowledged": true,
"insertedId": "5ab9cbfa31c2ab715d42129e"
}
Display the document to verify the string _id ?
db.demo460.find();
{ "_id": "5ab9cbfa31c2ab715d42129e" }
Example: Convert String to ObjectId
Use $toObjectId to convert the string _id to a proper ObjectId ?
db.demo460.aggregate([
{
$addFields: {
"convertedId": { $toObjectId: "$_id" }
}
}
]);
{
"_id": "5ab9cbfa31c2ab715d42129e",
"convertedId": ObjectId("5ab9cbfa31c2ab715d42129e")
}
Key Points
- The string must be exactly 24 characters and contain only hexadecimal characters (0-9, a-f).
- Use
$toObjectIdin aggregation pipelines for safe conversion. - Invalid strings will cause the aggregation to fail with a cast error.
Conclusion
Use the $toObjectId operator in MongoDB aggregation pipelines to convert valid 24-character hexadecimal strings to ObjectId. Ensure the string format is correct to avoid cast failures.
Advertisements
