On this page本页内容
$toObjectId¶New in version 4.0.版本4.0中的新功能。
Converts a value to an ObjectId. If the value cannot be converted to an ObjectId, $toObjectId errors. If the value is null or missing, $toObjectId returns null.
$toObjectId has the following syntax:语法如下所示:
The $toObjectId takes any valid expression.
The $toObjectId is a shorthand for the following $convert expression:
See also参阅
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:
{$toObjectId: "5ab9cbfa31c2ab715d42129e"} |
ObjectId(“5ab9cbfa31c2ab715d42129e”) |
{$toObjectId: "5ab9cbfa31c2ab715d42129"} |
Error |
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.