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

$map(式 演算子)

$map

配列内の各項目にを適用し、適用結果の配列を返します。

次の環境でホストされる配置には $map を使用できます。

  • MongoDB Atlas はクラウドでの MongoDB 配置のためのフルマネージド サービスです

  • MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン

  • MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン

$map式の構文は次のとおりです。

{ $map: { input: <expression>, as: <string>, in: <expression> } }
フィールド
仕様

input

配列に解決される

inputnull に解決されるか、欠落しているフィールドを参照する場合、$mapnull を返します。

input が配列以外、null 以外の値に解決される場合、パイプラインはエラーになります。

as

任意。input 配列の各要素を表す変数の名前。名前が指定されていない場合、変数名はデフォルトで this になります。

in

input 配列の各要素に適用される。式は、as に指定された変数名を使用して各要素を個別に参照します。

式の詳細については、「式 」を参照してください。

このページの例では、付属の 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 ]
}
]

前の例で使用された式の詳細については、以下を参照してください。

戻る

$ltrim

項目一覧