Mongo. how to check if field is a number

typeof in mongo returns object for array type also. To check if a field is a Number, run below query to see if it returns any result.

db.foo.find('Object.prototype.toString.call(this.bar) === "[object Number]"')

You can also see https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString


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 }}]})

you can use the alias "number" instead:

{ field: {$type:"number"}}

You can the type of a field bar by using

typeof db.foo.findOne().bar

http://docs.mongodb.org/manual/core/shell-types/#check-types-in-shell