目录
MongoDB $type 操作符概述
$type
是 MongoDB 提供的查询操作符,用于根据字段的数据类型进行筛选。它可以帮助用户根据文档中字段的类型(如字符串、数字、数组等)来进行查询操作。这对于某些特定类型的数据分析或清理工作非常有用。
$type
操作符接受两种类型的参数:
- 字符串格式:直接指定数据类型的名称(如
"string"
、"int"
等)。 - 数字格式:指定类型的编号。MongoDB 为每个数据类型分配了一个唯一的数字编号。
使用 $type 操作符的基本查询
db.collectionName.find({ field: { $type: "typeName" } })
例如,要查找 age
字段类型为整数的数据:
db.users.find({ age: { $type: "int" } })
查询不同数据类型的文档
$type
可以查询各种数据类型的字段。以下是一些常见的数据类型及其字符串表示:
"double"
:双精度浮点数"string"
:字符串"object"
:嵌套文档"array"
:数组"binData"
:二进制数据"undefined"
:未定义"objectId"
:ObjectId 类型"bool"
:布尔值"date"
:日期"null"
:空值"regex"
:正则表达式
例如,要查找 status
字段为布尔类型的文档:
db.users.find({ status: { $type: "bool" } })
常见数据类型和对应的类型编号
除了使用类型名称,$type
还可以通过数字编号来指定数据类型。以下是常见类型及其对应的编号:
类型名称 | 编号 |
---|---|
Double | 1 |
String | 2 |
Object | 3 |
Array | 4 |
BinData | 5 |
Undefined | 6 |
ObjectId | 7 |
Bool | 8 |
Date | 9 |
Null | 10 |
Regex | 11 |
DBRef | 12 |
JavaScript | 13 |
Symbol | 14 |
JavaScript (Code with scope) | 15 |
32-bit Integer | 16 |
Timestamp | 17 |
64-bit Integer | 18 |
Decimal128 | 19 |
MinKey | 255 |
MaxKey | 127 |
例如,查找 createdAt
字段类型为日期的文档(使用数字表示):
db.users.find({ createdAt: { $type: 9 } })
参考资料
如需更多帮助或信息,请访问 www.52kanjuqing.com。
发表回复