$type(聚合)
定义
行为
$type
与基于BSON类型匹配数组元素的$type
查询操作符不同,$type
聚合操作符不检查数组元素。相反,当将数组作为其参数传递时,$type
聚合操作符返回参数的类型,即"array"
。
如果参数是输入文档中缺失的字段,$type
返回字符串"missing"
。
以下表格显示了$type
输出对于几种常见的表达式类型
示例 | 结果 |
---|---|
{ $type: "a" } | "string" |
{ $type: /a/ } | "regex" |
{ $type: 1 } | "double" |
{ $type: NumberLong(627) } | "long" |
{ $type: { x: 1 } } | "object" |
{ $type: [ [ 1, 2, 3 ] ] } | "array" |
可用的类型
类型 | 数字 | 别名 | 说明 |
---|---|---|---|
双精度浮点型 | 1 | "double" | |
字符串 | 2 | "string" | |
对象 | 3 | "object" | |
数组 | 4 | "array" | |
二进制数据 | 5 | "binData" | |
未定义 | 6 | "undefined" | 已弃用。 |
ObjectId | 7 | "objectId" | |
布尔型 | 8 | "bool" | |
日期 | 9 | "date" | |
空值 | 10 | "null" | |
正则表达式 | 11 | "regex" | |
DBPointer | 12 | "dbPointer" | 已弃用。 |
JavaScript | 13 | "javascript" | |
符号 | 14 | "symbol" | 已弃用。 |
32位整数 | 16 | "int" | |
时间戳 | 17 | "timestamp" | |
64位整数 | 18 | "long" | |
Decimal128 | 19 | "decimal" | |
最小键值 | -1 | "minKey" | |
最大键值 | 127 | "maxKey" |
如果参数是输入文档中缺失的字段,$type
返回字符串"missing"
。
示例
此示例使用一个名为 集合 的名为 coll
,包含以下 文档:
{ _id: 0, a : 8 } { _id: 1, a : [ 41.63, 88.19 ] } { _id: 2, a : { a : "apple", b : "banana", c: "carrot" } } { _id: 3, a : "caribou" } { _id: 4, a : NumberLong(71) } { _id: 5 }
以下聚合操作使用 $type
操作符来显示所有文档中 a
字段的类型,作为 $project
阶段的操作。
db.coll.aggregate([{ $project: { a : { $type: "$a" } } }])
操作返回以下内容
{ _id: 0, "a" : "double" } { _id: 1, "a" : "array" } { _id: 2, "a" : "object" } { _id: 3, "a" : "string" } { _id: 4, "a" : "long" } { _id: 5, "a" : "missing" }