定義
$map配列内の各項目に式を適用し、適用結果の配列を返します。
互換性
次の環境でホストされる配置には $map を使用できます。
MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
$map式の構文は次のとおりです。
{ $map: { input: <expression>, as: <string>, in: <expression> } }
フィールド | 仕様 |
|---|---|
| 配列に解決される式。
|
| 任意。 |
|
|
式の詳細については、「式 」を参照してください。
例
配列の各要素に追加する
このページの例では、付属の sample_mflixサンプルデータセット のデータを使用します。このデータセットを自己管理型MongoDBデプロイにロードする 方法の詳細については、「サンプルデータセットをロードする 」を参照してください。サンプルデータベースに変更を加えた場合、このページの例を実行するには、データベースを削除して再作成する必要がある場合があります。
次の集計操作では、$map $add10location.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 truncatelocation.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 ] } ]
詳細
前の例で使用された式の詳細については、以下を参照してください。