Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
Click here >
Docs 菜单
Docs 主页
/ /

$map(表达式操作符)

$map

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

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

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

$map 表达式的语法如下:

{ $map: { input: <expression>, as: <string>, in: <expression> } }
字段
规范

input

解析为数组的表达式

如果 input 解析为 null 或指向缺失的字段,则 $map 返回 null

如果 input 解析为非数组、非 null 值,则管道将出错。

as

可选。 代表 input 数组中每个元素的变量名称。 如果未指定名称,则变量名称默认为this

in

应用于 input 数组中每个元素的表达式。 该表达式单独引用带有 as 中指定的变量名称的每个元素。

有关表达式的更多信息,请参阅表达式

本页上的示例使用 sample_mflix示例数据集 中的数据。有关如何将此数据集加载到自管理MongoDB 部署中的详细信息,请参阅加载示例数据集。如果对示例数据库进行了任何修改,则可能需要删除并重新创建数据库才能运行本页上的示例。

以下聚合操作使用$map$add 表达式将 添加到10 location.geo.coordinates大量中的每个元素:

db.theaters.aggregate( [
{
$match: {
theaterId: { $in: [ 1000, 1003, 1008 ] }
}
},
{
$project: {
_id: 0,
theaterId: 1,
adjustedCoordinates: {
$map: {
input: "$location.geo.coordinates",
as: "coord",
in: { $add: [ "$$coord", 10 ] }
}
}
}
},
{ $sort: { theaterId: 1 } }
] )
[
{ theaterId: 1000, adjustedCoordinates: [ -83.24565, 54.85466 ] },
{ theaterId: 1003, adjustedCoordinates: [ -66.512016, 48.29697 ] },
{ theaterId: 1008, adjustedCoordinates: [ -111.96328, 48.367649 ] }
]

以下聚合操作使用$maptruncate 大量中的每个元素location.geo.coordinates 为其整数:

db.theaters.aggregate( [
{
$match: {
theaterId: { $in: [ 1000, 1003, 1008 ] }
}
},
{
$project: {
_id: 0,
theaterId: 1,
integerCoordinates: {
$map: {
input: "$location.geo.coordinates",
as: "coord",
in: { $trunc: "$$coord" }
}
}
}
},
{ $sort: { theaterId: 1 } }
] )
[
{ theaterId: 1000, integerCoordinates: [ -93, 44 ] },
{ theaterId: 1003, integerCoordinates: [ -76, 38 ] },
{ theaterId: 1008, integerCoordinates: [ -121, 38 ] }
]

以下聚合操作使用$addFields 阶段添加新的genreScores 字段。该操作使用$map $multiply$add 和 应用到genres 大量中的每个元素,并根据每个类型名称的字符数计算分数:

db.movies.aggregate( [
{
$match: { runtime: { $gt: 1000 } }
},
{
$addFields: {
genreScores: {
$map: {
input: "$genres",
as: "genre",
in: {
$add: [
{ $multiply: [ { $strLenCP: "$$genre" }, 2 ] },
1
]
}
}
}
}
},
{ $project: { _id: 0, title: 1, genres: 1, genreScores: 1 } },
{ $sort: { title: 1 } }
] )
[
{
genres: [ 'Documentary', 'History', 'Sport' ],
title: 'Baseball',
genreScores: [ 23, 15, 11 ]
},
{
genres: [ 'Action', 'Adventure', 'Drama' ],
title: 'Centennial',
genreScores: [ 13, 19, 11 ]
}
]

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

后退

$ltrim

在此页面上