MongoDB $type 操作符


MongoDB 的 $type 操作符用于查询指定键的值的数据类型。

基本使用方法:

db.collection.find({ key: { $type: typeCode } })

其中, typeCode 是 MongoDB 数据类型的一个整数代码,下面是一些常见的代码和它们所表示的数据类型:

Code Type
1 Double
2 String
3 Object
4 Array
5 Binary data
6 Undefined
7 ObjectId
8 Boolean
9 Date
10 Null
11 Regular Exp.
12 JavaScript
13 Symbol
14 JavaScript
15 Min Key
16 Max Key

比如,如果你想查询数据库中指定键的数据类型是字符串型的文档,可以这样写:

db.collection.find({ key: { $type: 2 } })

可以使用类型的字符串名称来代替整数代码,如下所示:

db.collection.find({ key: { $type: "string" } })

$type 操作符还支持一些与特定类型相关的附加选项:

  • $exists:表示指定键是否存在,当值为 false 时,查询返回键不存在的文档,例如:

    db.collection.find({ key: { $exists: false } })
    
  • $regex:表示正则表达式,用于查询字符串型的数据,例如:

    db.collection.find({ key: { $type: "string", $regex: /^a/ } })
    

    在上面的例子中,我们查询了以字母 a 开头的字符串型数据。

  • $options:与 $regex 一起使用,用于修饰正则表达式。

    db.collection.find({ key: { $type: "string", $regex: /^a/i, $options: 'm' } })
    

在使用 $type 操作符时需要注意以下几点:

  • 该操作符只能用于查询键值的类型,不能用于查询嵌套文档中的类型
  • 其他操作符无法与 $type 一起使用
  • 该操作符可能会导致查询性能下降

参考文献: