$type
操作符用来查询某个字段是否是的指定BSON
类型。当文档的数据类型是高度的非结构化时,这非常的有用{ field: { $type: <BSON type> } }
,你可以通过数组或别名来指定BSON的type{ field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }
,这将匹配数组中BSON类型的任意一个
BSON type总结(version 3.2)
3.2版本可以使用别名或数字来指定BSON
类型,在3.2之前的版本只能使用数字来匹配。
Type | Number | Alias | Notes |
---|---|---|---|
Double | 1 | “double” | |
String | 2 | “string” | |
Object | 3 | “object” | |
Array | 4 | “array” | |
Binary data | 5 | “binData” | |
Undefined | 6 | “undefined” | 废弃 |
ObjectId | 7 | “objectId” | |
Boolean | 8 | “bool” | |
Date | 9 | “date” | |
Null | 10 | “null” | |
RegularExpression | 11 | “regex” | |
DBPointer | 12 | “dbPointer” | |
JavaScript | 13 | “javascript” | |
Sysmbol | 14 | “symbol” | 废弃 |
JavaScript(with scope) | 15 | “javascriptWithScope” | |
32-bit integer | 16 | “int” | |
Timestamp | 17 | “timestamp” | |
64-bit integer | 18 | “long” | |
Decimal128 | 19 | “decimal” | 3.4版本新增 |
Min key | -1 | “minKey” | |
Max Key | 127 | “maxKey” |
示例
源数据
[ |
查询zipCode字段是string的:
db.addressBook.find( { "zipCode" : { $type : 2 } } ); |
zipCode的BSON类型是double的:
db.addressBook.find( { "zipCode" : { $type : 1 } } ) |
使用number
类型别名匹配BSON类型是double``int
或long
的:
db.addressBook.find( { "zipCode" : { $type : "number" } } ) |
示例2
源数据
[ |
查询classAverage
字段是BSON类型string
或double
的:
db.grades.find( { "classAverage" : { $type : [ 2 , 1 ] } } ); |