$type(BSON 类型)
最后更新:2026-10-09
$type(BSON 类型)
$type 按 BSON 类型匹配字段值。`{ age: { $type: 'int' } }` 匹配 age 为 32 位整数的文档。类型可用别名(string、object、array、date、double 等)或数字代号(1 为 double、2 为 string)。注意字符串 '21' 与数字 21 是不同类型,这是常见混淆点。
| 分类 | 元素与求值 |
|---|---|
| MongoDB 版本 | 1.0+ |
| 示例语言 | mongosh (Shell) |
📝 语法
{ <字段>: { $type: <BSON类型> } }
⚙️ 参数
| 字段 | 要检查类型的文档字段名。 |
|---|---|
| BSON类型 | 类型别名或代号,如 'int'、'string'、'date'、'array'。 |
返回值:匹配的文档游标
▶ 示例
请在本地安装的 mongosh 中执行以下命令(需已启动 mongod):
// $type:年龄是整数的用户
// int 表示 32 位整数
db.users.find({ age: { $type: 'int' } })
// 多个类型:整数或双精度
db.users.find({ age: { $type: ['int', 'double'] } })
运行结果:
// 返回 age 为 int 类型的用户;第二个示例返回 int 或 double 类型的用户
📌 注意事项
- 数字类型细分:int、long、double、decimal,别混为一谈
- 字符串 '21' 与数字 21 是不同类型,$type 严格区分
- 可用别名或代号:'date' 等价于代号 9
🏷️ 相关标签
💡 相关案例
📚 相关教程
❓ 常见问题
Q$type 有哪些常用类型别名?
Adouble、string、object、array、binData、objectId、bool、date、null、regex、int、long、decimal、timestamp 等。
Q怎么查日期类型的字段?
A{ updatedAt: { $type: 'date' } }。
Q$type 能查 null 吗?
A能,'null' 匹配值为 null 的文档(字段需存在)。