在本章节中,我们将继续讨论 MongoDB 中条件操作符 $type。
$type 操作符用来选择字段值为指定 BSON 类型实例的文档。在处理数据类型不可预测的高度非结构化数据时,按数据类型查询非常有用。
$type 表达式的语法如下:
{ field: { $type: <BSON type> } }$type 表达式也可以接受一个 BSON 类型数组,语法如下:
{ field: { $type: [ <BSON type1> , <BSON type2>, ... ] } }MongoDB 中可以使用的数据类型如下表所示:

该示例查询 val 字段值为布尔类型的文档。
# 准备数据
test> db.col.insertMany([{name:"java",val:true}, {name:"c++",val:120}, {name:"php",val:"¥40"}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("64e706dd10366fa87109a12c"),
'1': ObjectId("64e706dd10366fa87109a12d"),
'2': ObjectId("64e706dd10366fa87109a12e")
}
}
test> db.col.find()
[
{
_id: ObjectId("64e706dd10366fa87109a12c"),
name: 'java',
val: true
},
{ _id: ObjectId("64e706dd10366fa87109a12d"), name: 'c++', val: 120 },
{
_id: ObjectId("64e706dd10366fa87109a12e"),
name: 'php',
val: '¥40'
}
]
# 查询 val 为布尔值的数据
test> db.col.find({val: {$type: "bool"}})
[
{
_id: ObjectId("64e706dd10366fa87109a12c"),
name: 'java',
val: true
}
]
test> db.col.find({val: {$type: 8}})
[
{
_id: ObjectId("64e706dd10366fa87109a12c"),
name: 'java',
val: true
}
]