AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

$arrayElemAt (표현식 연산자)

$arrayElemAt

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

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

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

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

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

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

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

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

  • If the <idx> expression resolves to zero or a positive integer, $arrayElemAt returns the element at the idx position, counting from the start of the array.

  • If the <idx> expression resolves to a negative integer, $arrayElemAt returns the element at the idx position, counting from the end of the array.

  • If idx exceeds the array bounds, $arrayElemAt does not return a result.

  • If the <array> expression resolves to an undefined array, $arrayElemAt returns null.

예시
결과

{ $arrayElemAt: [ [ 1, 2, 3 ], 0 ] }

1

{ $arrayElemAt: [ [ 1, 2, 3 ], -2 ] }

2

{ $arrayElemAt: [ [ 1, 2, 3 ], 15 ] }

{ $arrayElemAt: [ "$undefinedField", 0 ] }

null

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

db.users.insertMany( [
{ _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" }
]