Find by $ type number in mongodb
I have the following documents
> db.people.insert({name: "Bob"}) > db.people.insert({name: 42}) If I need to find by type String , I can use:
> db.people.find({name: { $type: 2 }) Where 2 - Type Number of String
But how can I find by type Number ?
> typeof db.people.findOne({name: 42}).name number There is no type Number in possible types .
upd . I tried to find 16 and 18 types. This does not work.
> db.people.find({ name: 42 }) { "_id" : ObjectId("509645ae5013826ee61d96ac"), "name" : 42 } > db.people.find({name: { $type: 16 }}) > db.people.find({name: { $type: 18 }}) JavaScript ( Number ) has only one numeric type , which is represented in binary form as an IEEE 754 (double) floating-point number.
In the BSON specification, this will be represented as double (type 1), so you can find:
db.people.find({name: { $type: 1 }}) There are several mongo shell mongo if you want to insert various BSON data types :
42 // Type 1: double (64-bit IEEE 754 floating point, 8 bytes) NumberInt(42) // Type 16: int32 (32-bit signed integer, 4 bytes) NumberLong(42) // Type 18: int64 (64-bit signed integer, 8 bytes) So for example:
db.people.insert({ name: 'default', num: 42 }) db.people.insert({ name: 'NumberLong', num: NumberLong(42) }) db.people.insert({ name: 'NumberInt', num: NumberInt(42) }) Different numeric representations will still match if you do find() for a number that can be represented in several formats (i.e. a 32-bit integer can also be represented as double or int64).
For instance:
db.people.find({num:42}) { "_id" : ObjectId("50965aa3038d8c8e85fd3f45"), "name" : "default", "num" : 42 } { "_id" : ObjectId("50965aa3038d8c8e85fd3f46"), "name" : "NumberLong", "num" : NumberLong(42) } { "_id" : ObjectId("50965aa3038d8c8e85fd3f47"), "name" : "NumberInt", "num" : 42 } However, if you find $type , the BSON view is different:
> db.people.find({num: { $type: 1 }}) { "_id" : ObjectId("50965aa3038d8c8e85fd3f45"), "name" : "default", "num" : 42 } > db.people.find({num: { $type: 16 }}) { "_id" : ObjectId("50965aa3038d8c8e85fd3f47"), "name" : "NumberInt", "num" : 42 } > db.people.find({num: { $type: 18 }}) { "_id" : ObjectId("50965aa3038d8c8e85fd3f46"), "name" : "NumberLong", "num" : NumberLong(42) } In javascript there is no real difference between int32 and int64. However, the Mongodb shell uses 32 bits unless otherwise specified (using the Number (..) constructor).
You should try to execute the query as follows:
db.people.find({name: { $type: 16 }) where 16 is the type code for an integer: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24type