- Reference >
- Operators >
- Aggregation Pipeline Operators >
- $toObjectId (aggregation)
$toObjectId (aggregation)¶
On this page
Definition¶
-
$toObjectId¶ New in version 4.0.
Converts a value to an
ObjectId. If the value cannot be converted to an ObjectId,$toObjectIderrors. If the value is null or missing,$toObjectIdreturns null.$toObjectIdhas the following syntax:The
$toObjectIdtakes any valid expression.The
$toObjectIdis a shorthand for the following$convertexpression:See also
Behavior¶
The following table lists the input types that can be converted to an ObjectId:
| Input Type | Behavior |
|---|---|
| String | Returns an ObjectId for the hexadecimal string of length 24. You cannot convert a string value that is not a hexadecimal string of length 24. |
The following table lists some conversion to date examples:
| Example | Results |
|---|---|
{$toObjectId: "5ab9cbfa31c2ab715d42129e"} |
ObjectId(“5ab9cbfa31c2ab715d42129e”) |
{$toObjectId: "5ab9cbfa31c2ab715d42129"} |
Error |
Example¶
Create a collection orders with the following documents:
The following aggregation operation on the orders collection
converts the _id to ObjectId before sorting by the value:
The operation returns the following documents:
Note
If the conversion operation encounters an error, the aggregation
operation stops and throws an error. To override this behavior, use
$convert instead.