对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

$type(表达式操作符)

$type

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

$type采用以下操作符表达式语法:

{ $type: <expression> }

参数可以是任何有效表达式

提示

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

如果参数是输入文档中缺失的字段,则$type 将返回字符串"missing"

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

例子
结果

{ $type: "a" }

"string"

{ $type: /a/ }

"regex"

{ $type: 1 }

"double"

{ $type: Long(627) }

"long"

{ $type: { x: 1 } }

"object"

{ $type: [ [ 1, 2, 3 ] ] }

"array"

注意

对于像 [ 1, 2, 3 ] 这样的文字数组,将表达式括在外面的数组括号中,以防止 MongoDB 将 [ 1, 2, 3 ] 解析为带有三个参数的参数列表 (1, 2, 3)。将数组 [ 1, 2, 3 ] 包裹在一个 $literal 表达式中也能达到同样的效果。

有关更多信息,请参阅运算符表达式事务语法形式

类型
数值
别名
注意

double

1

"double"

字符串

2

"string"

对象

3

"object"

阵列

4

"array"

二进制数据

5

"binData"

未定义

6

"undefined"

已弃用。

ObjectId

7

"objectId"

布尔

8

"bool"

Date

9

"date"

null

10

"null"

正则表达式

11

"regex"

数据库指针

12

"dbPointer"

已弃用。

JavaScript

13

"javascript"

符号

14

"symbol"

已弃用。

带作用域的 JavaScript

15

"javascriptWithScope"

已弃用。

32 位整数

16

"int"

时间戳

17

"timestamp"

64 位整型

18

"long"

Decimal128

19

"decimal"

Min key

-1

"minKey"

Max key

127

"maxKey"

如果参数是输入文档中缺失的字段,则$type 将返回字符串"missing"

此示例使用了一个名为 coll集合,其中包含以下文档:

db.coll.insertMany( [
{ _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 : Long(71) },
{ _id: 5, a : null },
{ _id: 6 }
] )

作为 $project 阶段的一部分,以下聚合操作使用 $type 操作符显示所有文档字段 a 的类型。

db.coll.aggregate([{
$project: {
a : { $type: "$a" }
}
}])
[
{ _id: 0, "a" : "int" },
{ _id: 1, "a" : "array" },
{ _id: 2, "a" : "object" },
{ _id: 3, "a" : "string" },
{ _id: 4, "a" : "long" },
{ _id: 5, "a" : "null" },
{ _id: 6, "a" : "missing" }
]

表达式不支持$exists操作符。要评估某个字段是否存在于表达式中,可以使用 missing 类型。

以下聚合操作使用 missing 类型将 a字段添加到上述 coll集合中缺少 a字段的文档。请注意,其中 a: null 的文档与缺少 a字段的文档不同。

db.coll.aggregate([
{
$addFields: {
a: {
$cond: {
if: { $eq: [{ $type: "$a" }, "missing"] },
then: [],
else: "$a"
}
}
}
}
])
[
{ _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 : Long(71) },
{ _id: 5, a : null },
{ _id: 6, a : [] }
]
给本页内容打分

在此页面上