$type

Definition

  • $type
  • $type selects documents where the value of thefield is an instance of the specified BSON type(s).Querying by data type is useful when dealing with highlyunstructured data where data types are not predictable.

A $type expression for a single BSON type hasthe following syntax:

Changed in version 3.2.

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

You can specify either the number or alias for the BSONtype

The $type expression can also accept an array of BSONtypes and has the following syntax:

  1. { field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }

The above query will match documents where the field value isany of the listed types. The types specified in the array can beeither numeric or string aliases.

See Querying by Multiple Data Type for an example.

Available Types describes the BSON types andtheir corresponding numeric and string aliases.

See also

If you wish to obtain the BSON type returnedby an operator expressionrather than filtering documents by their BSON type, use the$type aggregation operator.

Behavior

$type returns documents where the BSON type of the fieldmatches the BSON type passed to $type.

Arrays

For documents where field is an array, $type returnsdocuments in which at least one array element matches a type passed to$type.

Querying for the Array BSON Type

With MongoDB 3.6 and later, querying for $type: "array" returnsdocuments where the field itself is an array. Prior to MongoDB 3.6,$type: "array" returned documents where the field is an arraycontaining at least one element of type array. For example, giventhe following documents:

  1. { "data" : [ "values", [ "values" ] ] }
  2. { "data" : [ "values" ] }

With MongoDB 3.6 and later, the queryfind( {"data" : { $type : "array" } } ) returns both documents.Prior to MongoDB 3.6, the query returns only the first document.

Available Types

Starting in MongoDB 3.2, $type operator accepts string aliasesfor the BSON types in addition to the numbers corresponding to the BSONtypes. Previous versions only accepted the numbers corresponding to theBSON type. [1]

TypeNumberAliasNotes
Double1“double”
String2“string”
Object3“object”
Array4“array”
Binary data5“binData”
Undefined6“undefined”Deprecated.
ObjectId7“objectId”
Boolean8“bool”
Date9“date”
Null10“null”
Regular Expression11“regex”
DBPointer12“dbPointer”Deprecated.
JavaScript13“javascript”
Symbol14“symbol”Deprecated.
JavaScript (with scope)15“javascriptWithScope”
32-bit integer16“int”
Timestamp17“timestamp”
64-bit integer18“long”
Decimal12819“decimal”New in version 3.4.
Min key-1“minKey”
Max key127“maxKey”

$type supports the number alias, which will match against thefollowing BSON types:

  • double
  • 32-bit integer
  • 64-bit integer
  • decimal

For examples, see Examples.

[1]Starting in MongoDB 4.2, users can no longer use the query filter$type: 0 as a synonym for$exists:false. To query for null or missing fields, seeQuery for Null or Missing Fields.

MinKey and MaxKey

MinKey and MaxKeyare used in comparison operations and exist primarily for internal use.For all possible BSON element values, MinKey will always be thesmallest value while MaxKey will always be the greatest value.

Querying for minKey or maxKey with $typewill only return fields that matchthe special MinKey or MaxKey values.

Suppose that the data collection has two documentswith MinKey and MaxKey:

  1. { "_id" : 1, x : { "$minKey" : 1 } }
  2. { "_id" : 2, y : { "$maxKey" : 1 } }

The following query will return the document with _id: 1:

  1. db.data.find( { x: { $type: "minKey" } } )

The following query will return the document with _id: 2:

  1. db.data.find( { y: { $type: "maxKey" } } )

Examples

Querying by Data Type

The addressBook contains addresses and zipcodes, wherezipCode has string, int, double, and longvalues:

  1. db.addressBook.insertMany(
  2. [
  3. { "_id" : 1, address : "2030 Martian Way", zipCode : "90698345" },
  4. { "_id" : 2, address: "156 Lunar Place", zipCode : 43339374 },
  5. { "_id" : 3, address : "2324 Pluto Place", zipCode: NumberLong(3921412) },
  6. { "_id" : 4, address : "55 Saturn Ring" , zipCode : NumberInt(88602117) },
  7. { "_id" : 5, address : "104 Venus Drive", zipCode : ["834847278", "1893289032"]}
  8. ]
  9. )

The following queries return all documents where zipCode is theBSON type string or is an array containing an element ofthe specified type:

  1. db.addressBook.find( { "zipCode" : { $type : 2 } } );
  2. db.addressBook.find( { "zipCode" : { $type : "string" } } );

These queries return:

  1. { "_id" : 1, "address" : "2030 Martian Way", "zipCode" : "90698345" }
  2. { "_id" : 5, address : "104 Venus Drive", zipCOde : ["834847278", "1893289032"]}

The following queries return all documents where zipCode is theBSON type double or is an array containing an element ofthe specified type:

  1. db.addressBook.find( { "zipCode" : { $type : 1 } } )
  2. db.addressBook.find( { "zipCode" : { $type : "double" } } )

These queries return:

  1. { "_id" : 2, "address" : "156 Lunar Place", "zip" : 43339374 }

The following query uses the number alias to return documents wherezipCode is the BSON type double, int, or longor is an array containing an element of the specified types:

  1. db.addressBook.find( { "zipCode" : { $type : "number" } } )

These queries return:

  1. { "_id" : 2, address : "156 Lunar Place", zipCode : 43339374 }
  2. { "_id" : 3, address : "2324 Pluto Place", zipCode: NumberLong(3921412) }
  3. { "_id" : 4, address : "55 Saturn Ring" , zipCode : 88602117 }

Querying by Multiple Data Type

The grades collection contains names and averages, whereclassAverage has string, int, and double values:

  1. db.grades.insertMany(
  2. [
  3. { "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 },
  4. { "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" },
  5. { "_id" : 3, name : "Cathy Hart", classAverage: "94.06" },
  6. { "_id" : 4, name : "Drew Williams" , classAverage : 93 }
  7. ]
  8. )

The following queries return all documents where classAverage is theBSON type string or double or is an array containingan element of the specified types. The first query uses numeric aliaseswhile the second query uses string aliases.

  1. db.grades.find( { "classAverage" : { $type : [ 2 , 1 ] } } );
  2. db.grades.find( { "classAverage" : { $type : [ "string" , "double" ] } } );

These queries return the following documents:

  1. { "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 }
  2. { "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" }
  3. { "_id" : 3, name : "Cathy Hart", classAverage: "94.06" }

Querying by MinKey and MaxKey

The restaurants collection uses minKey for any grade that is afailing grade:

  1. {
  2. "_id": 1,
  3. "address": {
  4. "building": "230",
  5. "coord": [ -73.996089, 40.675018 ],
  6. "street": "Huntington St",
  7. "zipcode": "11231"
  8. },
  9. "borough": "Brooklyn",
  10. "cuisine": "Bakery",
  11. "grades": [
  12. { "date": new Date(1393804800000), "grade": "C", "score": 15 },
  13. { "date": new Date(1378857600000), "grade": "C", "score": 16 },
  14. { "date": new Date(1358985600000), "grade": MinKey(), "score": 30 },
  15. { "date": new Date(1322006400000), "grade": "C", "score": 15 }
  16. ],
  17. "name": "Dirty Dan's Donuts",
  18. "restaurant_id": "30075445"
  19. }

And maxKey for any grade that is the highest passing grade:

  1. {
  2. "_id": 2,
  3. "address": {
  4. "building": "1166",
  5. "coord": [ -73.955184, 40.738589 ],
  6. "street": "Manhattan Ave",
  7. "zipcode": "11222"
  8. },
  9. "borough": "Brooklyn",
  10. "cuisine": "Bakery",
  11. "grades": [
  12. { "date": new Date(1393804800000), "grade": MaxKey(), "score": 2 },
  13. { "date": new Date(1378857600000), "grade": "B", "score": 6 },
  14. { "date": new Date(1358985600000), "grade": MaxKey(), "score": 3 },
  15. { "date": new Date(1322006400000), "grade": "B", "score": 5 }
  16. ],
  17. "name": "Dainty Daisey's Donuts",
  18. "restaurant_id": "30075449"
  19. }

The following query returns any restaurant whose grades.grade fieldcontains minKey or is an array containing an element ofthe specified type:

  1. db.restaurants.find(
  2. { "grades.grade" : { $type : "minKey" } }
  3. )

This returns

  1. {
  2. "_id" : 1,
  3. "address" : {
  4. "building" : "230",
  5. "coord" : [ -73.996089, 40.675018 ],
  6. "street" : "Huntington St",
  7. "zipcode" : "11231"
  8. },
  9. "borough" : "Brooklyn",
  10. "cuisine" : "Bakery",
  11. "grades" : [
  12. { "date" : ISODate("2014-03-03T00:00:00Z"), "grade" : "C", "score" : 15 },
  13. { "date" : ISODate("2013-09-11T00:00:00Z"), "grade" : "C", "score" : 16 },
  14. { "date" : ISODate("2013-01-24T00:00:00Z"), "grade" : { "$minKey" : 1 }, "score" : 30 },
  15. { "date" : ISODate("2011-11-23T00:00:00Z"), "grade" : "C", "score" : 15 }
  16. ],
  17. "name" : "Dirty Dan's Donuts",
  18. "restaurant_id" : "30075445"
  19. }

The following query returns any restaurant whose grades.grade fieldcontains maxKey or is an array containing an element ofthe specified type:

  1. db.restaurants.find(
  2. { "grades.grade" : { $type : "maxKey" } }
  3. )

This returns

  1. {
  2. "_id" : 2,
  3. "address" : {
  4. "building" : "1166",
  5. "coord" : [ -73.955184, 40.738589 ],
  6. "street" : "Manhattan Ave",
  7. "zipcode" : "11222"
  8. },
  9. "borough" : "Brooklyn",
  10. "cuisine" : "Bakery",
  11. "grades" : [
  12. { "date" : ISODate("2014-03-03T00:00:00Z"), "grade" : { "$maxKey" : 1 }, "score" : 2 },
  13. { "date" : ISODate("2013-09-11T00:00:00Z"), "grade" : "B", "score" : 6 },
  14. { "date" : ISODate("2013-01-24T00:00:00Z"), "grade" : { "$maxKey" : 1 }, "score" : 3 },
  15. { "date" : ISODate("2011-11-23T00:00:00Z"), "grade" : "B", "score" : 5 }
  16. ],
  17. "name" : "Dainty Daisey's Donuts",
  18. "restaurant_id" : "30075449"
  19. }

Querying by Array Type

A collection named SensorReading contains the following documents:

  1. {
  2. "_id": 1,
  3. "readings": [
  4. 25,
  5. 23,
  6. [ "Warn: High Temp!", 55 ],
  7. [ "ERROR: SYSTEM SHUTDOWN!", 66 ]
  8. ]
  9. },
  10. {
  11. "_id": 2,
  12. "readings": [
  13. 25,
  14. 25,
  15. 24,
  16. 23
  17. ]
  18. },
  19. {
  20. "_id": 3,
  21. "readings": [
  22. 22,
  23. 24,
  24. []
  25. ]
  26. },
  27. {
  28. "_id": 4,
  29. "readings": []
  30. },
  31. {
  32. "_id": 5,
  33. "readings": 24
  34. }

The following query returns any document in which the readingsfield is an array, empty or non-empty.

  1. db.SensorReading.find( { "readings" : { $type: "array" } } )

The above query returns the following documents:

  1. {
  2. "_id": 1,
  3. "readings": [
  4. 25,
  5. 23,
  6. [ "Warn: High Temp!", 55 ],
  7. [ "ERROR: SYSTEM SHUTDOWN!", 66 ]
  8. ]
  9. },
  10. {
  11. "_id": 2,
  12. "readings": [
  13. 25,
  14. 25,
  15. 24,
  16. 23
  17. ]
  18. },
  19. {
  20. "_id": 3,
  21. "readings": [
  22. 22,
  23. 24,
  24. []
  25. ]
  26. },
  27. {
  28. "_id": 4,
  29. "readings": []
  30. }

In the documents with _id : 1, _id : 2, _id : 3, and_id : 4, the readings field is an array.

Additional Information