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
$typeto 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 Alias | BSON Type Number | Description |
|---|---|---|
| double | 1 | 64-bit floating point number |
| string | 2 | UTF-8 string |
| object | 3 | Embedded document |
| array | 4 | Array |
| binData | 5 | Binary data |
| undefined | 6 | Deprecated undefined |
| objectId | 7 | ObjectId |
| bool | 8 | Boolean |
| date | 9 | UTC datetime |
| null | 10 | Null value |
| regex | 11 | Regular expression |
| int | 16 | 32-bit integer |
| long | 18 | 64-bit integer |
| decimal | 19 | 128-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.