Skip to content

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 类型

类型数字字符串别名
Double1"double"
String2"string"
Object3"object"
Array4"array"
Binary5"binData"
ObjectId7"objectId"
Boolean8"bool"
Date9"date"
Null10"null"
Int3216"int"
Int6418"long"

匹配多种类型

javascript
db.users.find({
  score: { $type: ["int", "long", "double"] }
})

可用于清洗或校验数据,找出类型异常的文档。

下一节介绍 MongoDB Limit 与 Skip 方法