MongoDB 数据类型查询 — $type使用
MongoDB 使用过程中经常需要根据字段的类型来查询数据, 而MongoDB中查询字段类型是通过$type操作符来实现.
$type使用法语:
db.集合名.find({$type:类型值}); //这里的类型值能使用Number也能使用alias
举个例子:
db.person.find({address:{$type:2}}); //查询address字段数据类型为字符串
db.person.find({address:{$type:"string"}}); //查询address字段数据类型为字符串
再举个有点特殊的查询,关于null 查询的例子:
db.person.find({address:null}); //注意,这样查询会将没有 address 列的数据一并查询出来
db.person.find({address:{$exists:true, $eq:null}}); //这样查询的是 address 列值为null 的数据
db.person.find({address:{$type:10}}); //这样查询的是 address 列值为null 的数据
$type 有效的类型值,如下:
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” |
官网参考:https://docs.mongodb.com/manual/reference/operator/query/type/index.html