定义
$map对数组中的每个列项应用 表达式,并返回包含已应用结果的数组。
兼容性
可以使用 $map 查找托管在以下环境中的部署:
MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务
MongoDB Enterprise:基于订阅、自我管理的 MongoDB 版本
MongoDB Community:源代码可用、免费使用且可自行管理的 MongoDB 版本
语法
$map 表达式的语法如下:
{ $map: { input: <expression>, as: <string>, in: <expression> } }
字段 | 规范 |
|---|---|
| |
| 可选。 代表 |
| 应用于 |
有关表达式的更多信息,请参阅表达式。
示例
增加数组的每个元素
本页上的示例使用 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 ] } ]
了解详情
要了解上述示例中所用表达式的更多信息,请参阅: