MongoDB聚合运算符:$type

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"

可用的类型

类型数字别名说明
Double1“double”
String2“string”
Object3“object”
Array4“array”
Binary data5“binData”
Undefined6“undefined”已废弃
ObjectId7“objectId”
Boolean8“bool”
Date9“date”
Null10“null”
Regular Expression11“regex”
DBPointer12“dbPointer”已废弃
JavaScript13“javascript”
Symbol14“symbol”已废弃
32-bit integer16“int”
Timestamp17“timestamp”
64-bit integer18“long”
Decimal12819“decimal”
Min key-1“minKey”
Max key127“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" }
  • 16
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

原子星

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值