On this page
$type (aggregation)
在本页面
Definition
$type
- 3.4 版的新功能。
返回指定参数BSON type的字符串。
{ $type: <expression> }
参数可以是任何有效的expression。
Behavior
$type
$type查询运算符根据 BSON 类型匹配数组元素,而$type聚合运算符不检查数组元素。相反,当传递数组作为参数时,$type
聚合运算符返回参数的类型,即"array"
。
如果参数是 Importing 文档中缺少的字段,则$type返回字符串"missing"
。
下表显示了几种常见类型的表达式的$type输出:
Example | Results |
---|---|
{ $type: "a" } |
"string" |
{ $type: /a/ } |
"regex" |
{ $type: 1 } |
"double" |
{ $type: NumberLong(627) } |
"long" |
{ $type: { x: 1 } } |
"object" |
{ $type: [ [ 1, 2, 3 ] ] } |
"array" |
Note
对于[ 1, 2, 3 ]
之类的 Literals 数组,请将表达式括在一组外部数组括号中,以防止 MongoDB 将[ 1, 2, 3 ]
解析为具有三个参数(1, 2, 3
)的argument list。将数组[ 1, 2, 3 ]
包裹在$literal表达式中可获得相同的结果。
有关更多信息,请参见运算符表达式语法形式。
Available Types
Type | Number | Alias | Notes |
---|---|---|---|
Double | 1 | "double" | |
String | 2 | "string" | |
Object | 3 | "object" | |
Array | 4 | "array" | |
Binary data | 5 | "binData" | |
Undefined | 6 | "undefined" | Deprecated. |
ObjectId | 7 | "objectId" | |
Boolean | 8 | "bool" | |
Date | 9 | "date" | |
Null | 10 | "null" | |
Regular Expression | 11 | "regex" | |
DBPointer | 12 | "dbPointer" | Deprecated. |
JavaScript | 13 | "javascript" | |
Symbol | 14 | "symbol" | Deprecated. |
JavaScript(带范围) | 15 | "javascriptWithScope" | |
32-bit integer | 16 | "int" | |
Timestamp | 17 | "timestamp" | |
64-bit integer | 18 | "long" | |
Decimal128 | 19 | "decimal" | 3.4 版的新功能。 |
Min key | -1 | "minKey" | |
Max key | 127 | "maxKey" |
如果参数是 Importing 文档中缺少的字段,则$type返回字符串"missing"
。
Example
本示例使用名为coll
的collection和以下documents:
{ _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" }