MongoDB聚合运算符:$type

发布于:2024-05-19 ⋅ 阅读:(166) ⋅ 点赞:(0)

MongoDB聚合运算符:$type


$type聚合运算符用来返回指定参数的BSON类型的字符串。。

语法

{ $type: <expression> }
  • <expression>可以是任何合法的表达式。

使用

  • 不像查询操作符$type基于BSON类型匹配数组元素,$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"

可用的类型

类型 数字 别名 说明
Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” 已废弃
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
Regular Expression 11 “regex”
DBPointer 12 “dbPointer” 已废弃
JavaScript 13 “javascript”
Symbol 14 “symbol” 已废弃
32-bit integer 16 “int”
Timestamp 17 “timestamp”
64-bit integer 18 “long”
Decimal128 19 “decimal”
Min key -1 “minKey”
Max key 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 }

下面的聚合操作在$project阶段使用$type运算符显示字段a的类型。

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" }

网站公告

今日签到

点亮在社区的每一天
去签到