$type¶
On this page
Definition¶
-
$type
¶ Syntax:
{ field: { $type: <BSON type> } }
$type
selects the documents where the value of thefield
is the specified numeric BSON type. This is useful when dealing with highly unstructured data where data types are not predictable.Warning
Data models that associate a field name with different data types within a collection are strongly discouraged.
Without internal consistency complicates application code, and can lead to unnecessary complexity for application developers.
Behavior¶
Available Types¶
Refer to the following table for the available BSON types and their corresponding numbers.
Type | Number | Notes |
Double | 1 | |
String | 2 | |
Object | 3 | |
Array | 4 | |
Binary data | 5 | |
Undefined | 6 | Deprecated. |
Object id | 7 | |
Boolean | 8 | |
Date | 9 | |
Null | 10 | |
Regular Expression | 11 | |
JavaScript | 13 | |
Symbol | 14 | Deprecated. |
JavaScript (with scope) | 15 | |
32-bit integer | 16 | |
Timestamp | 17 | |
64-bit integer | 18 | |
Min key | 255 | Query with -1 . |
Max key | 127 |
Minimum and Maximum Values¶
MinKey
and MaxKey
compare less than and greater than all
other possible BSON element values, respectively, and exist
primarily for internal use.
To query if a field value is a MinKey
, you must use $type
with
-1
as in the following example:
Arrays¶
When applied to arrays, $type
matches any inner element that is of the
specified type. Without projection this means that the entire array
will match if any element has the right type. With projection, the
results will include just those
elements of the requested type.
Examples¶
Querying by Data Type¶
Consider the following query:
This will list all documents containing a tags
field that is either a string
or an array holding at least one string. If you only want to list documents where
tags
is an array, you could use $where
:
Queries that use $where
requires a complete collection scan
and uses Server-side JavaScript.
MinKey
and MaxKey
¶
The following operation sequence demonstrates both type comparison and the
special MinKey
and MaxKey
values:
Minimum Shard Key¶
To query for the minimum value of a shard key of a
sharded cluster, use the following operation when
connected to the mongos
: