Mongo. how to check if field is a number

mongodb, mongodb-query

Solution

You can use the $type operator to select based on the BSON type of the field, which should get you what you want.

So, for example, to find all strings:

db.collection.find( { field: { $type : 2 } } )

Or, to find all doubles (which is usually what numbers get stored as from the shell thanks to the default Javascript behavior), you would use:

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

Since there are two types of integer (potentially) you would need to go with something like this:

db.collection.find({$or : [{"field" : { $type : 16 }}, {"field" : { $type : 18 }}]})

Finally then, to get all numbers, integer or double:

db.collection.find({$or : [{"field" : { $type : 1 }}, {"field" : { $type : 16 }}, {"field" : { $type : 18 }}]})

Problem

How to select mongodb documents where field is a number? Some examples of the content of this field: "2", "a", "Z", 3

Original source