$type

Matches documents where the specified field is of the specified BSON type.

Syntax

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

Parameters

fieldstringrequired

The field name to check the type of

BSON typestringrequired

BSON type number (1-19) or string alias: "double", "string", "object", "array", "binData", "objectId", "bool", "date", "null", "regex", "int", "timestamp", "long", "decimal"

Examples

Find string fields

Match documents where name field is a string

Query:

db.products.find({ "name": { $type: "string" } })

Output:

Documents where the name field contains string values

Find numeric fields using type number

Match documents where price field is a double (type 1)

Query:

db.products.find({ "price": { $type: 1 } })

Output:

Documents where the price field contains double/float values

Find array fields

Match documents where tags field is an array

Query:

db.products.find({ "tags": { $type: "array" } })

Output:

Documents where the tags field is an array type

Find date fields

Match documents where createdDate field is a date

Query:

db.stores.find({ "createdDate": { $type: "date" } })

Output:

Documents where createdDate field contains date values

Multiple type matching

Match documents where field can be one of multiple types

Query:

db.products.find({ "price": { $type: ["int", "double", "long"] } })

Output:

Documents where price field is any numeric type

Check nested field types

Verify type of nested object fields

Query:

db.stores.find({ "location.lat": { $type: "double" } })

Output:

Documents where latitude field is a double within location object

Related