$toObjectId

Reference type:Cheat sheetFormat:Syntax + example + use case

Reference group: Conversion and type inspection

What it does

Converts valid 24-character hexadecimal strings to ObjectId.

Syntax

{$toObjectId: expression}

Use case

Migrate string references.

Important notes

Invalid strings cause conversion errors.

$toObjectId: practical example
{ $set: { customerObjectId: { $toObjectId: "$customerIdText" } } }
💡 Explanation Converts valid 24-character hexadecimal strings to ObjectId. When to use it Migrate string references. Caution Invalid strings cause conversion errors.
Key Takeaways
  • Converts valid 24-character hexadecimal strings to ObjectId.
  • Typical use: Migrate string references.