Definition
$toObjectId
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:{
$toObjectId: <expression>
}The
$toObjectId
takes any valid expression.The
$toObjectId
is a shorthand for the following$convert
expression:{ $convert: { input: <expression>, to: "objectId" } }
Tip
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 |
---|---|
| ObjectId("5ab9cbfa31c2ab715d42129e") |
| Error |
Example
Create a collection orders
with the following documents:
db.orders.insertMany( [
{ _id: "5ab9cbe531c2ab715d42129a", item: "apple", qty: 10 },
{ _id: ObjectId("5ab9d0b831c2ab715d4212a8"), item: "pie", qty: 5 },
{ _id: ObjectId("5ab9d2d331c2ab715d4212b3"), item: "ice cream", qty: 20 },
{ _id: "5ab9e16431c2ab715d4212b4", item: "almonds", qty: 50 },
] )
The following aggregation operation on the orders
collection converts the _id
to ObjectId before sorting by the value:
// Define stage to add convertedId field with converted _id value
idConversionStage = {
$addFields: {
convertedId: { $toObjectId: "$_id" }
}
};
// Define stage to sort documents by the converted qty values
sortStage = {
$sort: { "convertedId": -1 }
};
db.orders.aggregate( [
idConversionStage,
sortStage
] )
The operation returns the following documents:
{
_id: '5ab9e16431c2ab715d4212b4',
item: 'almonds',
qty: 50,
convertedId: ObjectId("5ab9e16431c2ab715d4212b4")
},
{
_id: ObjectId("5ab9d2d331c2ab715d4212b3"),
item: 'ice cream',
qty: 20,
convertedId: ObjectId("5ab9d2d331c2ab715d4212b3")
},
{
_id: ObjectId("5ab9d0b831c2ab715d4212a8"),
item: 'pie',
qty: 5,
convertedId: ObjectId("5ab9d0b831c2ab715d4212a8")
},
{
_id: '5ab9cbe531c2ab715d42129a',
item: 'apple',
qty: 10,
convertedId: ObjectId("5ab9cbe531c2ab715d42129a")
}
Note
If the conversion operation encounters an error, the aggregation operation stops and throws an error. To override this behavior, use $convert
instead.