Navigation
This version of the documentation is archived and no longer supported.

$type

Definition

$type

Syntax: { field: { $type: <BSON type> } }

$type selects the documents where the value of the field is an instance of the specified numeric BSON type. This is useful when dealing with highly unstructured data where data types are not predictable.

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:

db.collection.find( { field: { $type: -1 } } );

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:

db.inventory.find( { tags: { $type : 2 } } );

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:

db.inventory.find( { $where : "Array.isArray(this.tags)" } );

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:

> db.test.insert( [ { x : 3 },
                  { x : 2.9 },
                  { x : new Date() },
                  { x : true },
                  { x : MaxKey },
                  { x : MinKey } ] );

> db.test.find().sort( { x : 1 } );
{ "_id" : ObjectId("4b031563ce8de6586fb002cb"), "x" : { $minKey : 1 } }
{ "_id" : ObjectId("4b03155dce8de6586fb002c7"), "x" : 2.9 }
{ "_id" : ObjectId("4b03154cce8de6586fb002c6"), "x" : 3 }
{ "_id" : ObjectId("4b031566ce8de6586fb002c9"), "x" : true }
{ "_id" : ObjectId("4b031563ce8de6586fb002c8"), "x" : ISODate("2012-07-25T23:42:03Z") }
{ "_id" : ObjectId("4b031563ce8de6586fb002ca"), "x" : { $maxKey : 1 } }

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:

use config
db.chunks.find( { "min.shardKey": { $type: -1 } } )

Additional Information

find(), insert(), $where, BSON, shard key, sharded cluster .