MongoDB $type 操作符
MongoDB $type 操作符
在 MongoDB 中,$type 操作符用于匹配字段的数据类型。它允许查询某个字段的值是否属于特定的数据类型。
1. 语法
{ field: { $type: <dataType> } }
其中:
field:要检查的字段。<dataType>:可以是数字类型的 BSON 代码或字符串(从 MongoDB 3.2 开始支持字符串)。
2. 常见数据类型
MongoDB $type 操作符支持多种 BSON 数据类型:
| BSON 代码 | 类型名称(字符串) | 说明 |
|---|---|---|
| 1 | "double" | 双精度浮点数 |
| 2 | "string" | 字符串 |
| 3 | "object" | 文档(对象) |
| 4 | "array" | 数组 |
| 5 | "binData" | 二进制数据 |
| 7 | "objectId" | ObjectId |
| 8 | "bool" | 布尔值(true 或 false) |
| 9 | "date" | 日期 |
| 10 | "null" | 空值(null) |
| 11 | "regex" | 正则表达式 |
| 12 | "dbPointer" | 数据库指针(已废弃) |
| 13 | "javascript" | JavaScript 代码 |
| 14 | "symbol" | 符号(已废弃) |
| 15 | "javascriptWithScope" | 带作用域的 JavaScript 代码(已废弃) |
| 16 | "int" | 32 位整数 |
| 17 | "timestamp" | 时间戳 |
| 18 | "long" | 64 位整数 |
| 19 | "decimal" | Decimal128 精确小数 |
| 21 | "javascriptWithScope" | JavaScript 代码(已废弃) |
| 127 | "maxKey" | 最大键值 |
| 255 | "minKey" | 最小键值 |
3. 使用示例
示例 1:查询 price 字段的数据类型为 double(双精度浮点数)
db.products.find({ price: { $type: "double" } })
或
db.products.find({ price: { $type: 1 } })
解释:
- 查询
price字段的类型是double(BSON 代码1)。 - 如果
price不是double(例如是int或string),则不会匹配。
示例 2:查询 name 字段的数据类型为 string
db.users.find({ name: { $type: "string" } })
或
db.users.find({ name: { $type: 2 } })
解释:
- 只匹配
name字段值为字符串的文档。
示例 3:查询 createdAt 字段是 date 类型
db.orders.find({ createdAt: { $type: "date" } })
或
db.orders.find({ createdAt: { $type: 9 } })
解释:
- 仅匹配
createdAt字段值是日期(Date类型)的文档。
示例 4:查询 tags 字段的数据类型为 array
db.posts.find({ tags: { $type: "array" } })
或
db.posts.find({ tags: { $type: 4 } })
解释:
- 仅返回
tags字段值是数组的文档。
示例 5:查询 age 字段的数据类型是 int 或 long
db.users.find({ age: { $type: ["int", "long"] } })
或
db.users.find({ age: { $type: [16, 18] } })
解释:
$type允许传递一个数组,查询age字段的数据类型是int(32 位整数)或long(64 位整数)。- 如果
age是double类型,则不会匹配。
示例 6:查询 status 字段的数据类型是 bool(布尔值)
db.orders.find({ status: { $type: "bool" } })
或
db.orders.find({ status: { $type: 8 } })
解释:
- 仅返回
status字段值为true或false的文档。
4. $type 的作用
✅ 1. 确保字段的数据类型正确
如果你的应用程序依赖某个字段的数据类型,比如 createdAt 必须是 date,就可以使用 $type 进行检查:
db.orders.find({ createdAt: { $type: "date" } })
如果 createdAt 被存储成字符串,这个查询就不会返回该文档。
✅ 2. 检查数据库中的异常数据
在 MongoDB 中,字段的数据类型可能不一致,比如 price 可能被错误地存储为 string 而不是 double。可以使用 $type 检测:
db.products.find({ price: { $type: "string" } })
如果返回了数据,说明 price 字段存在异常。
✅ 3. 查询多种可能类型的数据
有时候,某个字段可能会存储不同类型的数据,比如 age 可能是 int 或 long。可以使用 $type 查询所有可能的类型:
db.users.find({ age: { $type: ["int", "long"] } })
5. 结论
$type用于查询字段的数据类型,可帮助检测错误数据、保证数据一致性。- 可以使用 BSON 代码(如
1代表double)或字符串(如"double")。 $type也支持数组查询,匹配多个数据类型。- 可用于排查数据异常、检查字段类型、优化查询。
在实际开发中,使用 $type 结合 find() 可以帮助你确保数据类型符合预期,减少数据错误,提高查询准确性! 🚀
更多详细内容请关注其他相关文章!