

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# \$1arrayElemAt
<a name="arrayElemAt"></a>

Amazon DocumentDB의 `$arrayElemAt` 연산자를 사용하면 인덱스 위치를 기준으로 배열에서 요소를 검색할 수 있습니다. 이는 문서의 배열 필드 내에서 특정 요소에 액세스해야 할 때 특히 유용합니다.

**파라미터**
+ `array`: 요소를 검색할 입력 배열입니다.
+ `index`: 검색할 요소의 0 기반 인덱스 위치입니다. 이 값은 음수가 아닌 정수여야 합니다.

## 예제(MongoDB 쉘)
<a name="arrayElemAt-examples"></a>

이 예제에서는 `$arrayElemAt` 연산자를 사용하여 `miles` 컬렉션의 `flight_miles` 배열에서 특정 요소를 검색하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.miles.insertMany([
  { "_id" : 1, "member_since" : ISODate("1987-01-01T00:00:00Z"), "credit_card" : false, "flight_miles" : [ 1205, 2560, 880 ]},
  { "_id" : 2, "member_since" : ISODate("1982-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 2560, 890, 2780 ]},
  { "_id" : 3, "member_since" : ISODate("1999-01-01T00:00:00Z"), "credit_card" : true, "flight_miles" : [ 1205, 880 ]}
]);
```

**쿼리 예제**

```
db.miles.aggregate([
  { $project: {
    "_id": 1,
    "first_mile": { $arrayElemAt: [ "$flight_miles", 0 ] },
    "last_mile": { $arrayElemAt: [ "$flight_miles", -1 ] }
  }}
]);
```

**출력**

```
{ "_id" : 1, "first_mile" : 1205, "last_mile" : 880 }
{ "_id" : 2, "first_mile" : 1205, "last_mile" : 2780 }
{ "_id" : 3, "first_mile" : 1205, "last_mile" : 880 }
```

이 예제에서는 `$arrayElemAt` 연산자를 사용하여 각 문서에 대한 `flight_miles` 배열의 첫 번째 및 마지막 요소를 검색합니다.

## 코드 예제
<a name="arrayElemAt-code"></a>

`$arrayElemAt` 명령을 사용하기 위한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

------
#### [ Node.js ]

```
const { MongoClient } = require('mongodb');

async function example() {
  const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false');
  const db = client.db('test');
  const collection = db.collection('miles');

  const result = await collection.aggregate([
    { $project: {
      "_id": 1,
      "first_mile": { $arrayElemAt: [ "$flight_miles", 0 ] },
      "last_mile": { $arrayElemAt: [ "$flight_miles", -1 ] }
    }}
  ]).toArray();

  console.log(result);
  client.close();
}

example();
```

------
#### [ Python ]

```
from pymongo import MongoClient

def example():
    client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false')
    db = client.mydatabase
    collection = db.miles

    result = list(collection.aggregate([
        { "$project": {
            "_id": 1,
            "first_mile": { "$arrayElemAt": [ "$flight_miles", 0 ] },
            "last_mile": { "$arrayElemAt": [ "$flight_miles", -1 ] }
        }}
    ]))

    print(result)
    client.close()

example()
```

------