0
0
MongodbHow-ToBeginner · 4 min read

How to Use $type Operator in MongoDB Queries

In MongoDB, use the $type operator in a query to filter documents based on the BSON data type of a field. It accepts either a string alias or a numeric code representing the data type, such as "string" or 2. This helps find documents where a field matches a specific type.
📐

Syntax

The $type operator is used inside a query filter to specify the data type of a field you want to match. It can be used like this:

  • { field: { $type: } }

Here, field is the name of the field to check, and <type> is either a string alias (like "string", "int") or a numeric BSON type code (like 2 for string, 16 for int).

json
{
  field: { $type: <type> }
}
💻

Example

This example shows how to find documents in a collection where the age field is stored as an integer type.

mongodb
db.users.find({ age: { $type: "int" } })
Output
[ { "_id": 1, "name": "Alice", "age": 30 }, { "_id": 3, "name": "Charlie", "age": 25 } ]
⚠️

Common Pitfalls

Common mistakes when using $type include:

  • Using incorrect type names or codes that MongoDB does not recognize.
  • Confusing string aliases with numeric codes; both are valid but must be correct.
  • Expecting $type to convert types; it only filters by existing data types.

For example, this query is incorrect because "integer" is not a valid alias:

mongodb
db.users.find({ age: { $type: "integer" } })  // Incorrect

// Correct usage:
db.users.find({ age: { $type: "int" } })
📊

Quick Reference

Type AliasBSON Type NumberDescription
double164-bit floating point number
string2UTF-8 string
object3Embedded document
array4Array
binData5Binary data
undefined6Deprecated undefined
objectId7ObjectId
bool8Boolean
date9UTC datetime
null10Null value
regex11Regular expression
int1632-bit integer
long1864-bit integer
decimal19128-bit decimal floating point

Key Takeaways

Use $type in queries to filter documents by the BSON data type of a field.
You can specify the type using either string aliases or numeric BSON type codes.
Common aliases include "string", "int", "bool", and "date".
$type does not convert data types; it only matches existing types.
Check MongoDB documentation for valid type names and codes to avoid errors.