문서 메뉴
문서 홈
/
MongoDB 매뉴얼
/ / /

$arrayElemAt (애그리게이션)

이 페이지의 내용

  • 정의
  • 호환성
  • 구문
  • 행동
  • 예제
  • 다음도 참조하세요.
$arrayElemAt

지정된 배열 인덱스에 있는 요소를 반환합니다.

다음 환경에서 호스팅되는 배포에 $arrayElemAt 사용할 수 있습니다.

  • MongoDB Atlas: 클라우드에서의 MongoDB 배포를 위한 완전 관리형 서비스

  • MongoDB Enterprise: MongoDB의 구독 기반 자체 관리 버전

  • MongoDB Community: MongoDB의 소스 사용 가능 무료 자체 관리 버전

$arrayElemAt 의 구문은 다음과 같습니다:

{ $arrayElemAt: [ <array>, <idx> ] }

<array> 표현식은 배열로 해석되는 모든 유효한 표현식일 수 있습니다.

<idx> 표현식은 정수로 해석되는 모든 유효한 표현식일 수 있습니다.

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

  • <idx> 표현식이 0 또는 양의 정수로 해석되는 경우 $arrayElemAt 는 배열의 시작부터 계산하여 idx 위치에 있는 요소를 반환합니다.

  • <idx> 표현식이 음의 정수로 확인되는 경우, $arrayElemAt(은)는 배열의 끝부터 계산하여 idx 위치의 요소를 반환합니다.

  • idx 이(가) 배열 경계를 초과하면 $arrayElemAt 은(는) 결과를 반환하지 않습니다.

  • <array> 표현식이 정의되지 않은 배열로 해석되면 $arrayElemAtnull 를 반환합니다.

예제
결과
{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] }
1
{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] }
2
{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] }
{ $arrayElemAt: [ "$undefinedField", 0 ] }
null

users라는 이름의 컬렉션에 다음 문서가 포함되어 있습니다.

{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] }
{ "_id" : 2, "name" : "li", favorites: [ "apples", "pudding", "pie" ] }
{ "_id" : 3, "name" : "ahn", favorites: [ "pears", "pecans", "chocolate", "cherries" ] }
{ "_id" : 4, "name" : "ty", favorites: [ "ice cream" ] }

다음 예제에서는 favorites 배열의 첫 번째 및 마지막 요소를 반환합니다.

db.users.aggregate([
{
$project:
{
name: 1,
first: { $arrayElemAt: [ "$favorites", 0 ] },
last: { $arrayElemAt: [ "$favorites", -1 ] }
}
}
])

이 연산은 다음과 같은 결과를 반환합니다.

{ "_id" : 1, "name" : "dave123", "first" : "chocolate", "last" : "apples" }
{ "_id" : 2, "name" : "li", "first" : "apples", "last" : "pie" }
{ "_id" : 3, "name" : "ahn", "first" : "pears", "last" : "cherries" }
{ "_id" : 4, "name" : "ty", "first" : "ice cream", "last" : "ice cream" }
← $anyElementTrue (애그리게이션)