MongoDB $toObjectId Operator

Beginner
5 min read
Updated: Oct 2026
3 examples
Live preview

What Is $toObjectId?

$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" } }.

Remember
$toObjectId = hex string → ObjectId

{ $toObjectId: <expression> }

input  → 24-char hex string
output → ObjectId("...")
null / missing → null
invalid length/format → pipeline error

Common use: string FK → match ObjectId _id
($lookup / joins)
UsePrefer
Hex string → ObjectId$toObjectId
ObjectId → hex string$toString
Convert with onError / onNull$convert

How to Use $toObjectId in MongoDB

Convert the hex string, then sort, match, or join on the ObjectId.

  1. Choose an expression stage ($addFields or $project).
  2. Pass a 24-character hex string field to $toObjectId.
  3. Optional: sort, match, or use the result in $lookup.
  4. If some strings may be invalid, prefer $convert with onError.
PieceRequired?Role
$toObjectIdYesConvert expression → ObjectId (or null)
ExpressionYes24-char hex string (or null/missing)
$convertNoSame 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 }

Cheat Sheet

Keep these facts handy while converting to ObjectId.

TopicDetail
TypeAggregation expression (not a find filter)
Syntax{ $toObjectId: <expression> }
Shorthand for{ $convert: { input: <e>, to: "objectId" } }
Valid input24-character hexadecimal string
Sample"5ab9cbfa31c2ab715d42129e" → ObjectId
InvalidWrong length / non-hex → error
Nullnull → null

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.

Result
input = "5ab9cbe531c2ab715d42129a"
$toObjectId → ObjectId("5ab9cbe531c2ab715d42129a")

{ convertedId: ObjectId("5ab9cbe531c2ab715d42129a") }

Worked Walkthrough — String IDs to ObjectId

Two orders store _id as a hex string. Convert so you can sort by ObjectId order (like the MongoDB docs pattern).

Calculation
Documents:
  { _id: "5ab9cbe531c2ab715d42129a", item: "apple" }
  { _id: "5ab9e16431c2ab715d4212b4", item: "almonds" }

$toObjectId("5ab9cbe531c2ab715d42129a")
  → ObjectId("5ab9cbe531c2ab715d42129a")

$toObjectId("5ab9e16431c2ab715d4212b4")
  → ObjectId("5ab9e16431c2ab715d4212b4")

Sort convertedId descending → almonds, then apple

MongoDB Examples

Insert sample orders with string hex IDs, convert with $toObjectId, then sort. Run these in mongosh in order.

Example 1 — Sample Data

Two orders use a 24-character hex string as _id (common when IDs arrive from JSON/APIs as text).

mongosh
db.orders.insertMany([
  { _id: "5ab9cbe531c2ab715d42129a", item: "apple", qty: 10 },
  { _id: "5ab9e16431c2ab715d4212b4", item: "almonds", qty: 50 }
]);

How the Data Is Stored in MongoDB

After the insert, MongoDB keeps two documents in orders. Run find() to see them:

mongosh
db.orders.find()

Read the rows like this:

FieldExamplesPlain English
_id24-char hex stringsID stored as text, not ObjectId yet
item"apple", "almonds"Product name
qty10, 50Quantity

How It Works

  1. Insert two orders. insertMany stores hex strings in _id.
  2. Type is string. These look like ObjectIds but are still plain strings in BSON.
  3. Ready to convert. The next example turns them into real ObjectId values.

Example 2 — Convert with $toObjectId

Goal: add a convertedId field as a BSON ObjectId for every order.

mongosh
db.orders.aggregate([
  {
    $addFields: {
      convertedId: { $toObjectId: "$_id" }
    }
  }
]);

How It Works

  1. Read each string _id. Values come from Example 1.
  2. Convert to ObjectId. $toObjectId parses the 24-char hex string.
  3. Type changes. convertedId is a real ObjectId; original _id stays a string.
  4. Ready to sort/join. ObjectId values compare and match correctly with other ObjectIds.

Example 3 — Sort by ObjectId

Convert first, then sort by convertedId descending (almonds before apple for these sample IDs).

mongosh
db.orders.aggregate([
  {
    $addFields: {
      convertedId: { $toObjectId: "$_id" }
    }
  },
  {
    $sort: { convertedId: -1 }
  }
]);

How It Works

  1. Same conversion. Stage one builds convertedId like Example 2.
  2. Sort on ObjectId. $sort: { convertedId: -1 } orders by ObjectId bytes.
  3. Why convert first? Sorting raw hex strings can differ from ObjectId ordering in edge cases; ObjectId type is the correct key.
  4. 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.

Performance Notes

ApproachCostBest for
$toObjectId per queryPer-document convertCleaning imported hex ID strings
Store ObjectIdCheapest long-termKeys you join/sort often
$convert + onErrorSlightly more workDirty / 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.

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.

Next: $toString

Convert values to strings in an aggregation pipeline.

$toString tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful