Search for document that has field of type using $type in MongoDB

Search for document that has field of type using $type in MongoDB

$type Selects documents if a field is of the specified type. For example you want to select all the documents that have the field name of type "string".

The $type operator takes a number or a string representation. You will find a list of all the possible values in the end of this snippet.

Inserting Documents

db.articles.insertMany([
{ name: "article 1" },
{ name: 5},
{ name: "article 2"}
])

Search for document containing the value

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

Result

{ "_id" : ObjectId("5e31cd67f098cf25b5b434dd"), "name" : "article 1" }
{ "_id" : ObjectId("5e31cd67f098cf25b5b434df"), "name" : "article 2" }

MongoDB field types

Type Number Alias Notes
Double 1 “double”  
String 2 “string”  
Object 3 “object”  
Array 4 “array”  
Binary data 5 “binData”  
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”  
Boolean 8 “bool”  
Date 9 “date”  
Null 10 “null”  
Regular Expression 11 “regex”  
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”  
Symbol 14 “symbol” Deprecated.
JavaScript (with scope) 15 “javascriptWithScope”  
32-bit integer 16 “int”  
Timestamp 17 “timestamp”  
64-bit integer 18 “long”  
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”  
Max key 127 “maxKey”