On this page
$map (aggregation)
在本页面
Definition
$map
- 将expression应用于数组中的每个项目,并返回具有所应用结果的数组。
$map表达式具有以下语法:
{ $map: { input: <expression>, as: <string>, in: <expression> } }
Field | Specification |
---|---|
input |
解析为数组的expression。 |
as |
可选的。 variable的名称,代表input 数组的每个单独元素。如果未指定名称,则变量名称默认为this 。 |
in |
expression应用于input 数组的每个元素。该表达式使用as 中指定的变量名称分别引用每个元素。 |
有关表达式的更多信息,请参见Expressions。
Examples
使用$ map 添加到数组的每个元素
在mongoShell 程序中,使用以下文档创建一个名为grades
的示例集合:
db.grades.insertMany([
{ _id: 1, quizzes: [ 5, 6, 7 ] },
{ _id: 2, quizzes: [ ] },
{ _id: 3, quizzes: [ 3, 8, 9 ] }
])
以下聚合操作使用$map和$add表达式将quizzes
数组中的每个元素增加2
。
db.grades.aggregate(
[
{ $project:
{ adjustedGrades:
{
$map:
{
input: "$quizzes",
as: "grade",
in: { $add: [ "$$grade", 2 ] }
}
}
}
}
]
)
此操作返回以下结果:
{ "_id" : 1, "adjustedGrades" : [ 7, 8, 9 ] }
{ "_id" : 2, "adjustedGrades" : [ ] }
{ "_id" : 3, "adjustedGrades" : [ 5, 10, 11 ] }
使用$ map 截断每个数组元素
在mongoShell 程序中,使用以下文档创建一个名为deliveries
的示例集合:
db.deliveries.insertMany([
{ "_id" : 1, "city" : "Bakersfield", "distances" : [ 34.57, 81.96, 44.24 ] },
{ "_id" : 2, "city" : "Barstow", "distances" : [ 73.28, 9.67, 124.36 ] },
{ "_id" : 3, "city" : "San Bernadino", "distances" : [ 16.04, 3.25, 6.82 ] }
])
以下聚合操作使用$map到truncate distances
数组中的每个元素为其整数。
db.deliveries.aggregate(
[
{ $project:
{ city: "$city",
integerValues:
{ $map:
{
input: "$distances",
as: "decimalValue",
in: { $trunc: "$$decimalValue" }
}
}
}
}
]
)
此操作返回以下结果:
{ "_id" : 1, "city" : "Bakersfield", "integerValues" : [ 34, 81, 44 ] }
{ "_id" : 2, "city" : "Barstow", "integerValues" : [ 73, 9, 124 ] }
{ "_id" : 3, "city" : "San Bernadino", "integerValues" : [ 16, 3, 6 ] }
使用$ map 将摄氏温度转换为华氏温度
在mongoShell 程序中,使用以下文档创建一个名为temperatures
的示例集合:
db.temperatures.insertMany([
{ "_id" : 1, "date" : ISODate("2019-06-23"), "tempsC" : [ 4, 12, 17 ] },
{ "_id" : 2, "date" : ISODate("2019-07-07"), "tempsC" : [ 14, 24, 11 ] },
{ "_id" : 3, "date" : ISODate("2019-10-30"), "tempsC" : [ 18, 6, 8 ] }
])
以下聚合操作使用$addFields阶段向名为tempsF
的文档中添加一个新字段,该字段包含tempsC
数组中元素的华氏等效值。要将摄氏温度转换为华氏温度,该操作使用_7 至$add 32
分别将$map至$multiply摄氏温度值。
db.temperatures.aggregate( [
{ $addFields:
{
"tempsF":
{ $map:
{
input: "$tempsC",
as: "tempInCelsius",
in: { $add: [ { $multiply: [ "$$tempInCelsius", 9/5 ] }, 32 ] }
}
}
}
}
] )
此操作返回以下结果:
{ "_id" : 1, "date" : ISODate("2019-06-23T00:00:00Z"), "tempsC : [ 4, 12, 17 ], "tempsF" : [ 39.2, 53.6, 62.6 ] }
{ "_id" : 2, "date" : ISODate("2019-07-07T00:00:00Z"), "tempsC" : [ 14, 24, 11 ], "tempsF" : [ 57.2, 75.2, 51.8 ] }
{ "_id" : 3, "date" : ISODate("2019-10-30T00:00:00Z"), "tempsC" : [ 18, 6, 8 ], "tempsF" : [ 64.4, 42.8, 46.4 ] }