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

$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 ] }]

以下聚合操作使用$map 将truncate 数组中的每个元素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 ] }]

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