$type (aggregation)

Definition

  • $type

New in version 3.4.

Returns a string that specifies the BSON type of the argument.

$type has the following operator expressionsyntax:

  1. { $type: <expression> }

The argument can be any valid expression.

See also

If you wish to filter documents by their BSON type rather than returning the type of an expression,use the $type query operator.

Behavior

$type

Unlike the $type query operator, which matches arrayelements based on their BSON type, the $typeaggregation operator does not examine array elements. Instead,when passed an array as its argument, the $type aggregationoperator returns the type of the argument, i.e. "array".

If the argument is a field that is missing in the input document,$type returns the string "missing".

The following table shows the $type output for severalcommon types of expressions:

ExampleResults
{ $type: "a" }"string"
{ $type: /a/ }"regex"
{ $type: 1 }"double"
{ $type: NumberLong(627) }"long"
{ $type: { x: 1 } }"object"
{ $type: [ [ 1, 2, 3 ] ] }"array"

Note

In the case of a literal array such as [ 1, 2, 3 ],enclose the expression in an outer setof array brackets to prevent MongoDB from parsing[ 1, 2, 3 ] as anargument listwith three arguments (1, 2, 3). Wrapping the array[ 1, 2, 3 ] in a $literal expressionachieves the same result.

See operator expression syntax forms for more information.

Available Types

TypeNumberAliasNotes
Double1“double”
String2“string”
Object3“object”
Array4“array”
Binary data5“binData”
Undefined6“undefined”Deprecated.
ObjectId7“objectId”
Boolean8“bool”
Date9“date”
Null10“null”
Regular Expression11“regex”
DBPointer12“dbPointer”Deprecated.
JavaScript13“javascript”
Symbol14“symbol”Deprecated.
JavaScript (with scope)15“javascriptWithScope”
32-bit integer16“int”
Timestamp17“timestamp”
64-bit integer18“long”
Decimal12819“decimal”New in version 3.4.
Min key-1“minKey”
Max key127“maxKey”

If the argument is a field that is missing in the input document,$type returns the string "missing".

Example

This example uses a collection named coll withthe following documents:

  1. { _id: 0, a : 8 }
  2. { _id: 1, a : [ 41.63, 88.19 ] }
  3. { _id: 2, a : { a : "apple", b : "banana", c: "carrot" } }
  4. { _id: 3, a : "caribou" }
  5. { _id: 4, a : NumberLong(71) }
  6. { _id: 5 }

The following aggregation operation uses the $typeoperator to display the type of field a for all documentsas part of the $project stage.

  1. db.coll.aggregate([{
  2. $project: {
  3. a : { $type: "$a" }
  4. }
  5. }])

The operation returns the following:

  1. { _id: 0, "a" : "double" }
  2. { _id: 1, "a" : "array" }
  3. { _id: 2, "a" : "object" }
  4. { _id: 3, "a" : "string" }
  5. { _id: 4, "a" : "long" }
  6. { _id: 5, "a" : "missing" }