$toObjectId (aggregation)

Definition

  • $toObjectId

New in version 4.0.

Converts a value to an ObjectId. If the value cannot beconverted to an ObjectId, $toObjectId errors. If thevalue is null or missing, $toObjectId returns null.

$toObjectId has the following syntax:

  1. {
  2. $toObjectId: <expression>
  3. }

The $toObjectId takes any valid expression.

The $toObjectId is a shorthand for the following$convert expression:

  1. { $convert: { input: <expression>, to: "objectId" } }

See also

$convert

Behavior

The following table lists the input types that can be converted to anObjectId:

Input TypeBehavior
StringReturns an ObjectId for the hexadecimal string of length 24.You cannot convert a string value that is not a hexadecimalstring of length 24.

The following table lists some conversion to date examples:

ExampleResults
{$toObjectId: "5ab9cbfa31c2ab715d42129e"}ObjectId(“5ab9cbfa31c2ab715d42129e”)
{$toObjectId: "5ab9cbfa31c2ab715d42129"}Error

Example

Create a collection orders with the following documents:

  1. db.orders.insert( [
  2. { _id: "5ab9cbe531c2ab715d42129a", item: "apple", qty: 10 },
  3. { _id: ObjectId("5ab9d0b831c2ab715d4212a8"), item: "pie", qty: 5 },
  4. { _id: ObjectId("5ab9d2d331c2ab715d4212b3"), item: "ice cream", qty: 20 },
  5. { _id: "5ab9e16431c2ab715d4212b4", item: "almonds", qty: 50 },
  6. ] )

The following aggregation operation on the orders collectionconverts the _id to ObjectId before sorting by the value:

  1. // Define stage to add convertedId field with converted _id value
  2.  
  3. idConversionStage = {
  4. $addFields: {
  5. convertedId: { $toObjectId: "$_id" }
  6. }
  7. };
  8.  
  9. // Define stage to sort documents by the converted qty values
  10.  
  11. sortStage = {
  12. $sort: { "convertedId": -1 }
  13. };
  14.  
  15.  
  16. db.orders.aggregate( [
  17. idConversionStage,
  18. sortStage
  19. ])

The operation returns the following documents:

  1. { "_id" : "5ab9e16431c2ab715d4212b4", "item" : "almonds", "qty" : 50, "convertedId" : ObjectId("5ab9e16431c2ab715d4212b4") }
  2. { "_id" : ObjectId("5ab9d2d331c2ab715d4212b3"), "item" : "ice cream", "qty" : 20, "convertedId" : ObjectId("5ab9d2d331c2ab715d4212b3") }
  3. { "_id" : ObjectId("5ab9d0b831c2ab715d4212a8"), "item" : "pie", "qty" : 5, "convertedId" : ObjectId("5ab9d0b831c2ab715d4212a8") }
  4. { "_id" : "5ab9cbe531c2ab715d42129a", "item" : "apple", "qty" : 10, "convertedId" : ObjectId("5ab9cbe531c2ab715d42129a") }

Note

If the conversion operation encounters an error, the aggregationoperation stops and throws an error. To override this behavior, use$convert instead.