Appearance
MongoDB $type 操作符
按类型筛选
$type 根据 BSON 类型筛选字段,类型可用数字或字符串表示:
javascript
db.users.find({ age: { $type: "int" } })
db.users.find({ age: { $type: "number" } }) // int/long/double 等数值
db.users.find({ createdAt: { $type: "date" } })
db.users.find({ name: { $type: "string" } })常用 BSON 类型
| 类型 | 数字 | 字符串别名 |
|---|---|---|
| Double | 1 | "double" |
| String | 2 | "string" |
| Object | 3 | "object" |
| Array | 4 | "array" |
| Binary | 5 | "binData" |
| ObjectId | 7 | "objectId" |
| Boolean | 8 | "bool" |
| Date | 9 | "date" |
| Null | 10 | "null" |
| Int32 | 16 | "int" |
| Int64 | 18 | "long" |
匹配多种类型
javascript
db.users.find({
score: { $type: ["int", "long", "double"] }
})可用于清洗或校验数据,找出类型异常的文档。
下一节介绍 MongoDB Limit 与 Skip 方法。