$toObjectId is a MongoDB aggregation expression that converts a 24-character hex string to a BSON ObjectId. It is shorthand for { $convert: { input: <expr>, to: "objectId" } }.
Pass a 24-character hex string field to $toObjectId.
Optional: sort, match, or use the result in $lookup.
If some strings may be invalid, prefer $convert with onError.
Piece
Required?
Role
$toObjectId
Yes
Convert expression → ObjectId (or null)
Expression
Yes
24-char hex string (or null/missing)
$convert
No
Same conversion with error/null handling
Pseudocode
Pseudocode
for each document:
x = evaluate(expression)
if x is null or missing:
result = null
else if x is 24-char hex string:
result = ObjectId(x)
else:
error // aggregation fails
emit { ..., field: result }
Reference
Cheat Sheet
Keep these facts handy while converting to ObjectId.
Topic
Detail
Type
Aggregation expression (not a find filter)
Syntax
{ $toObjectId: <expression> }
Shorthand for
{ $convert: { input: <e>, to: "objectId" } }
Valid input
24-character hexadecimal string
Sample
"5ab9cbfa31c2ab715d42129e" → ObjectId
Invalid
Wrong length / non-hex → error
Null
null → null
Try it
Live Preview
Pick a hex string and see the ObjectId-style result (format check demo—same idea as $toObjectId).
Simulates $toObjectId validation (24 hex chars). Not a real MongoDB server.
Same conversion. Stage one builds convertedId like Example 2.
Sort on ObjectId.$sort: { convertedId: -1 } orders by ObjectId bytes.
Why convert first? Sorting raw hex strings can differ from ObjectId ordering in edge cases; ObjectId type is the correct key.
Join tip. The same conversion is what you often need before $lookup when a foreign key is a string.
Edge Cases & Pitfalls
Check these before using $toObjectId in production pipelines.
format
Must be 24 hex characters
Shorter strings like "5ab9cbfa31c2ab715d42129" fail. Use $convert with onError for messy data.
null
Null and missing become null
$toObjectId returns null for null/missing inputs—it does not invent an ObjectId.
types
String ≠ ObjectId in matches
A string foreign key will not equal an ObjectId _id. Convert one side before $lookup or $match.
reverse
Need a string again? Use $toString
$toString turns an ObjectId back into its 24-character hex form.
Analysis
Performance Notes
Approach
Cost
Best for
$toObjectId per query
Per-document convert
Cleaning imported hex ID strings
Store ObjectId
Cheapest long-term
Keys you join/sort often
$convert + onError
Slightly more work
Dirty / nullable ID strings
Prefer storing real ObjectId values when you control writes. Converting on every read is fine for cleanup, but avoid repeated string→ObjectId work on hot join paths.
Remember
Key Takeaways
Role: convert a 24-char hex string to ObjectId.
Format: wrong length or non-hex → error.
Joins: convert string FKs before matching ObjectId keys.
Shorthand: same as $convert to "objectId".
One line:$toObjectId answers “turn this hex string into a real ObjectId so types match.”
Frequently Asked Questions
$toObjectId converts a value to a BSON ObjectId inside an aggregation pipeline. It is commonly used when IDs are stored as hex strings but need to match ObjectId fields.
The input must be a valid 24-character hexadecimal string, such as "5ab9cbfa31c2ab715d42129e". Shorter, longer, or non-hex strings cause a conversion error.
$toObjectId is shorthand for { $convert: { input: <expr>, to: "objectId" } }. Use $convert with onError when some strings may not be valid ObjectIds.
$toObjectId returns null when the input is null or missing. It does not throw an error for null input.
Joins compare types strictly. A string foreign key will not match an ObjectId _id until you convert one side—often with $toObjectId.
Yes. Use $toString on an ObjectId when you need the 24-character hex string form.