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 배포를 위한 완전 관리형 서비스

$map 표현식의 구문은 다음과 같습니다.

{ $map: { input: <expression>, as: <string>, in: <expression> } }
필드
사양

input

배열로 해석되는 표현식 입니다.

input 값이 null로 확인되거나 누락된 필드를 나타내는 경우 $mapnull을 반환합니다.

input이 배열과 null이 아닌 값으로 해석되면 파이프라인 오류가 발생합니다.

as

선택 사항. input 배열의 각 개별 요소를 나타내는 변수의 이름입니다. 이름을 지정하지 않으면 변수 이름은 기본적으로 this가 됩니다.

in

input 배열의 각 요소에 적용되는 표현식입니다. 이 표현식은 as에 지정된 변수 이름을 사용하여 각 요소를 개별적으로 참조합니다.

표현식에 대한 자세한 내용은 표현식을 참조하세요 .

이 페이지의 예제에서는 sample_mflix 샘플 데이터 세트 의 데이터를 사용합니다. 이 데이터 세트를 자체 관리형 MongoDB deployment 에 로드하는 방법에 대한 자세한 내용은 샘플 데이터 세트 로드를 참조하세요. 샘플 데이터베이스를 수정한 경우 이 페이지의 예제를 실행 하려면 데이터베이스를 삭제하고 다시 만들어야 할 수 있습니다.

다음 집계 작업은 표현식 과 함께 $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 ]
}
]

이전 예시에서 사용된 표현식에 대해 자세히 알아보려면 다음을 참조하세요.

돌아가기

$ltrim

이 페이지의 내용