MongoDB $type Aggregation Pipeline Operator

In MongoDB, the $type aggregation pipeline operator returns the BSON type of its argument.

You can use it to find out the type of a given field.

Example

Suppose we have a collection called cats with the following document:

{
	"_id" : ObjectId("60173c09c8eb4369cf6ad9e0"),
	"name" : "Scratch",
	"born" : ISODate("2021-01-03T23:30:15.123Z"),
	"weight" : 30
}

We can use the following code to return the types of those fields:

db.cats.aggregate(
  [
    {
      $project:
        { 
          _id: { $type: "$_id" },
          name: { $type: "$name" },
          born: { $type: "$born" },
          weight: { $type: "$weight" }
        }
    }
  ]
).pretty()

Result:

{
	"_id" : "objectId",
	"name" : "string",
	"born" : "date",
	"weight" : "double"
}

Example 2

Here’s another example that contains various fields of differing BSON types.

We have a collection called types with the following document:

{
	"_id" : ObjectId("601738d7c8eb4369cf6ad9de"),
	"double" : 123.75,
	"string" : "123",
	"boolean" : true,
	"date" : ISODate("2020-12-31T23:30:15.123Z"),
	"integer" : 123,
	"long" : NumberLong(123),
	"decimal" : NumberDecimal("123.75"),
	"object" : {
		"a" : 1
	},
	"array" : [
		1,
		2,
		3
	]
}

For the purpose of this article, I’ve named each field to reflect its BSON type.

We can now use the following code to return the types of those fields:

db.types.aggregate(
  [
    {
      $project:
        { 
          _id: { $type: "$_id" },
          double: { $type: "$double" },
          string: { $type: "$string" },
          boolean: { $type: "$boolean" },
          date: { $type: "$date" },
          integer: { $type: "$integer" },
          long: { $type: "$long" },
          decimal: { $type: "$decimal" },
          object: { $type: "$object" },
          array: { $type: "$array" }
        }
    }
  ]
).pretty()

Result:

{
	"_id" : "objectId",
	"double" : "double",
	"string" : "string",
	"boolean" : "bool",
	"date" : "date",
	"integer" : "int",
	"long" : "long",
	"decimal" : "decimal",
	"object" : "object",
	"array" : "array"
}

Filtering by Type

There’s also a $type element query operator that allows you to filter a collection of documents based on BSON type.

Check for Numbers

If you just want to check to see if a value is a number, see MongoDB $isNumber.