在mongodb中找到$ type number

ck3*_*k3g 5 mongodb

我有以下文件

> db.people.insert({name: "Bob"})
> db.people.insert({name: 42})
Run Code Online (Sandbox Code Playgroud)

如果我需要按类型查找String我可以使用:

> db.people.find({name: { $type: 2 })
Run Code Online (Sandbox Code Playgroud)

其中2是字符串的类型数

但是我怎么能按类型找到Number

> typeof db.people.findOne({name: 42}).name
number
Run Code Online (Sandbox Code Playgroud)

没有任何类型number可能的类型.

upd:我试过16种和18种类型.这不行.

> db.people.find({ name: 42 })
{ "_id" : ObjectId("509645ae5013826ee61d96ac"), "name" : 42 }
> db.people.find({name: { $type: 16 }})
> db.people.find({name: { $type: 18 }})
Run Code Online (Sandbox Code Playgroud)

Ste*_*nie 8

There is only one numeric type in JavaScript (Number), which is represented in binary as an IEEE 754 floating point number (double).

In the BSON spec this will be represented as a double (type 1), so you should be able to find with:

db.people.find({name: { $type: 1 }})
Run Code Online (Sandbox Code Playgroud)

There are some mongo shell helpers if you want to insert different 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)
Run Code Online (Sandbox Code Playgroud)

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) })
Run Code Online (Sandbox Code Playgroud)

The different numeric representations will still match if you do a find() on a number that can be represented in multiple formats (i.e. a 32-bit integer can also be represented as a double or int64).

For example:

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
}
Run Code Online (Sandbox Code Playgroud)

However if you find by $type, the BSON representation 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)
}
Run Code Online (Sandbox Code Playgroud)