$toObjectId

The `$toObjectId` operator converts a specified value into an ObjectId.

Syntax

{
  $toObjectId: <expression>
}

Parameters

expressionstringrequired

The specified string value to convert into an ObjectId.

Examples

Sample Data

{
  "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
  "name": "First Up Consultants | Beverage Shop"
}

Convert string to ObjectId

Convert the first 24 alphanumeric characters in the _id field to ObjectId.

This query removes dashes and converts a substring to ObjectId.

Query:

db.stores.aggregate([{
  $match: { _id: "b0107631-9370-4acd-aafa-8ac3511e623d" }
}, {
  $project: {
    idAsObjectId: {
      $toObjectId: {
        $substr: [{
          $replaceAll: {
            input: "$_id",
            find: "-",
            replacement: ""
          }
        }, 0, 24]
      }
    }
  }
}])

Output:

[
  {
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "idAsObjectId": "ObjectId('b010763193704acdaafa8ac3')"
  }
]

Related