$type (aggregation)

在本页面

Definition

  • $type
    • 3.4 版的新功能。

返回指定参数BSON type的字符串。

$type具有以下运算符表达式语法

{ $type: <expression> }

参数可以是任何有效的expression

See also

如果您希望通过文档BSON type过滤文档,而不是返回表达式的类型,请使用$type查询运算符。

Behavior

$type

$type查询运算符根据 BSON 类型匹配数组元素,而$type聚合运算符不检查数组元素。相反,当传递数组作为参数时,$type聚合运算符返回参数的类型,即"array"

如果参数是 Importing 文档中缺少的字段,则$type返回字符串"missing"

下表显示了几种常见类型的表达式的$type输出:

ExampleResults
{ $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

TypeNumberAliasNotes
Double1"double"
String2"string"
Object3"object"
Array4"array"
Binary data5"binData"
Undefined6"undefined"Deprecated.
ObjectId7"objectId"
Boolean8"bool"
Date9"date"
Null10"null"
Regular Expression11"regex"
DBPointer12"dbPointer"Deprecated.
JavaScript13"javascript"
Symbol14"symbol"Deprecated.
JavaScript(带范围)15"javascriptWithScope"
32-bit integer16"int"
Timestamp17"timestamp"
64-bit integer18"long"
Decimal12819"decimal"3.4 版的新功能。
Min key-1"minKey"
Max key127"maxKey"

如果参数是 Importing 文档中缺少的字段,则$type返回字符串"missing"

Example

本示例使用名为collcollection和以下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" }