정의
$map배열의 각 항목에 표현식을 적용하고 결과가 적용된 배열을 반환합니다.
호환성
다음 환경에서 호스팅되는 배포에 $map 사용할 수 있습니다.
MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스
MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전
MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전
구문
$map 표현식의 구문은 다음과 같습니다.
{ $map: { input: <expression>, as: <string>, in: <expression> } }
필드 | 사양 |
|---|---|
| 배열로 해석되는 표현식 입니다.
|
| 선택 사항. |
|
|
표현식에 대한 자세한 내용은 표현식을 참조하세요 .
예시
배열의 각 요소에 추가
이 페이지의 예제에서는 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 ] } ]
자세히 알아보기
이전 예시에서 사용된 표현식에 대해 자세히 알아보려면 다음을 참조하세요.