mongo中使用$type查询字段的BSON类型

$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”

示例

源数据

[
{ "_id" : 1, address : "2030 Martian Way", zipCode : "90698345" },
{ "_id" : 2, address: "156 Lunar Place", zipCode : 43339374 },
{ "_id" : 3, address : "2324 Pluto Place", zipCode: NumberLong(3921412) },
{ "_id" : 4, address : "55 Saturn Ring" , zipCode : NumberInt(88602117) }
]

查询zipCode字段是string的:

db.addressBook.find( { "zipCode" : { $type : 2 } } );
//等价于
db.addressBook.find( { "zipCode" : { $type : "string" } } );

//返回结果
{ "_id" : 1, "address" : "2030 Martian Way", "zipCode" : "90698345" }

zipCode的BSON类型是double的:

db.addressBook.find( { "zipCode" : { $type : 1 } } )
//等价于
db.addressBook.find( { "zipCode" : { $type : "double" } } )
//返回结果
{ "_id" : 2, "address" : "156 Lunar Place", "zip" : 43339374 }

使用number类型别名匹配BSON类型是double``intlong的:

db.addressBook.find( { "zipCode" : { $type : "number" } } )
//返回结果
{ "_id" : 2, address : "156 Lunar Place", zipCode : 43339374 }
{ "_id" : 3, address : "2324 Pluto Place", zipCode: NumberLong(3921412) }
{ "_id" : 4, address : "55 Saturn Ring" , zipCode : 88602117 }

示例2

源数据

[
{ "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 },
{ "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" },
{ "_id" : 3, name : "Cathy Hart", classAverage: "94.06" },
{ "_id" : 4, name : "Drew Williams" , classAverage : 93 }
]

查询classAverage字段是BSON类型stringdouble的:

db.grades.find( { "classAverage" : { $type : [ 2 , 1 ] } } );
//等价于
db.grades.find( { "classAverage" : { $type : [ "string" , "double" ] } } );
//返回结果
{ "_id" : 1, name : "Alice King" , classAverage : 87.333333333333333 }
{ "_id" : 2, name : "Bob Jenkins", classAverage : "83.52" }
{ "_id" : 3, name : "Cathy Hart", classAverage: "94.06" }