Docs 菜单

Docs 主页开发应用程序MongoDB Manual

$map(聚合)

在此页面上

  • 定义
  • 兼容性
  • 语法
  • 举例
  • 增加数组的每个元素
  • 截断每个数组元素
  • 将摄氏温度转换为华氏温度
  • 了解详情
$map

对数组中的每个项目应用表达式,并返回包含已应用结果的数组。

可以使用 $map 查找托管在以下环境中的部署:

  • MongoDB Atlas :用于在云中部署 MongoDB 的完全托管服务

$map表达式采用以下语法:

{ $map: { input: <expression>, as: <string>, in: <expression> } }
字段
规范
input
解析为数组的表达式
as
可选。 代表 input 数组中每个元素的变量名称。 如果未指定名称,则变量名称默认为this
in
应用于 input 数组中每个元素的表达式。 该表达式单独引用带有 as 中指定的变量名称的每个元素。

有关表达式的更多信息,请参阅表达式运算符。

mongosh中,使用以下文档创建名为grades的示例集合:

db.grades.insertMany( [
{ quizzes: [ 5, 6, 7 ] },
{ quizzes: [ ] },
{ quizzes: [ 3, 8, 9 ] }
] )

以下聚合操作使用$map$add表达式,将quizzes数组中的每个元素递增2

db.grades.aggregate( [
{
$project: {
adjustedGrades: {
$map: {
input: "$quizzes",
as: "grade",
in: { $add: [ "$$grade", 2 ] }
}
}
}
}
] )

此操作返回以下结果:

[
{
_id: ObjectId("6390b8f7237da390c6869a62"),
adjustedGrades: [ 7, 8, 9 ]
},
{
_id: ObjectId("6390b8f7237da390c6869a63"),
adjustedGrades: []
},
{
_id: ObjectId("6390b8f7237da390c6869a64"),
adjustedGrades: [ 5, 10, 11 ]
}
]

mongosh中,使用以下文档创建名为deliveries的示例集合:

db.deliveries.insertMany( [
{
"city" : "Bakersfield",
"distances" : [ 34.57, 81.96, 44.24 ]
},
{
"city" : "Barstow",
"distances" : [ 73.28, 9.67, 124.36 ]
},
{
"city" : "San Bernadino",
"distances" : [ 16.04, 3.25, 6.82 ]
}
] )

以下聚合操作使用$mapdistances数组中的每个元素truncate为其整数。

db.deliveries.aggregate( [
{
$project: {
city: "$city",
integerValues: {
$map: {
input: "$distances",
as: "decimalValue",
in: { $trunc: "$$decimalValue" }
}
}
}
}
] )

此操作返回以下结果:

[
{
_id: ObjectId("6390b9b1237da390c6869a65"),
city: 'Bakersfield',
integerValues: [ 34, 81, 44 ]
},
{
_id: ObjectId("6390b9b1237da390c6869a66"),
city: 'Barstow',
integerValues: [ 73, 9, 124 ]
},
{
_id: ObjectId("6390b9b1237da390c6869a67"),
city: 'San Bernadino',
integerValues: [ 16, 3, 6 ]
}
]

mongosh中,使用以下文档创建名为temperatures的示例集合:

db.temperatures.insertMany( [
{
"date" : ISODate("2019-06-23"),
"tempsC" : [ 4, 12, 17 ]
},
{
"date" : ISODate("2019-07-07"),
"tempsC" : [ 14, 24, 11 ]
},
{
"date" : ISODate("2019-10-30"),
"tempsC" : [ 18, 6, 8 ]
}
] )

以下聚合操作使用$addFields阶段向文档添加一个名为tempsF的新字段,其中包含tempsC数组中元素的华氏度等效值。要将摄氏温度转换为华氏温度,该操作使用$map将摄氏温度值$multiply 9/5 ,然后$add 32

db.temperatures.aggregate( [
{
$addFields: {
"tempsF": {
$map: {
input: "$tempsC",
as: "tempInCelsius",
in: {
$add: [ { $multiply: [ "$$tempInCelsius", 9/5 ] }, 32 ]
}
}
}
}
}
] )

此操作返回以下结果:

[
{
_id: ObjectId("6390ba11237da390c6869a68"),
date: ISODate("2019-06-23T00:00:00.000Z"),
tempsC: [ 4, 12, 17 ],
tempsF: [ 39.2, 53.6, 62.6 ]
},
{
_id: ObjectId("6390ba11237da390c6869a69"),
date: ISODate("2019-07-07T00:00:00.000Z"),
tempsC: [ 14, 24, 11 ],
tempsF: [ 57.2, 75.2, 51.8 ]
},
{
_id: ObjectId("6390ba11237da390c6869a6a"),
date: ISODate("2019-10-30T00:00:00.000Z"),
tempsC: [ 18, 6, 8 ],
tempsF: [ 64.4, 42.8, 46.4 ]
}
]

要了解上述示例中所用表达式的更多信息,请参阅:

← $ltrim(聚合)