$type (BSON Type)
Last updated: 2026-10-09
$type (BSON Type)
$type matches documents where a field value is of a given BSON type. `{ age: { $type: 'int' } }` matches documents where age is a 32-bit integer. Use type aliases (string, object, array, date, double) or numeric codes (1 double, 2 string). The string '21' and the number 21 are different types — a common confusion.
| Category | Element & Evaluation |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ <field>: { $type: <BSON type> } }
⚙️ Parameters
| field | The document field whose type to test. |
|---|---|
| BSON type | A type alias or code, e.g. 'int', 'string', 'date', 'array'. |
Returns:Cursor of matching documents
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $type: users whose age is an integer
// int means a 32-bit integer
db.users.find({ age: { $type: 'int' } })
// Multiple types: int or double
db.users.find({ age: { $type: ['int', 'double'] } })
Output:
// Returns users whose age is int; the second query matches int or double
📌 Notes
- Numeric types are split into int, long, double, decimal — don't lump them
- The string '21' and number 21 are different types; $type is strict
- Aliases or codes both work: 'date' equals code 9
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat are the common $type aliases?
Adouble, string, object, array, binData, objectId, bool, date, null, regex, int, long, decimal, timestamp, etc.
QHow do I query a date-typed field?
A{ updatedAt: { $type: 'date' } }.
QCan $type match null?
AYes, 'null' matches documents whose field value is null (the field must exist).