

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

# \$1slice
<a name="slice-update"></a>

`$slice` 업데이트 연산자는 크기를 제한하여 배열을 수정합니다. `$push` 연산자와 함께 사용하면 배열의 요소 수를 제한하여 지정된 수의 가장 최근 또는 가장 오래된 요소만 유지합니다.

**파라미터**
+ `field`: 수정할 배열 필드입니다.
+ `count`: 유지할 최대 요소 수입니다. 양수 값은 첫 번째 N 요소를 유지하고 음수 값은 마지막 N 요소를 유지합니다.

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

다음 예제에서는에서 `$slice` 업데이트 연산자를 사용하여 최근 점수의 고정 크기 배열을 `$push` 유지하는 방법을 보여줍니다.

**샘플 문서 생성**

```
db.students.insertOne({
  _id: 1,
  name: "Alice",
  scores: [85, 90, 78]
});
```

**쿼리 예제**

```
db.students.updateOne(
  { _id: 1 },
  {
    $push: {
      scores: {
        $each: [92, 88],
        $slice: -3
      }
    }
  }
)
```

**출력**

```
{
  "_id" : 1,
  "name" : "Alice",
  "scores" : [ 78, 92, 88 ]
}
```

이 예제에서 `$slice: -3` 한정자는 배열에 새 값을 푸시한 후 마지막 세 요소만 유지합니다.

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

`$slice` 업데이트 연산자 사용에 대한 코드 예제를 보려면 사용하려는 언어의 탭을 선택합니다.

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

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

async function updateDocument() {
  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('students');

  await collection.updateOne(
    { _id: 1 },
    {
      $push: {
        scores: {
          $each: [92, 88],
          $slice: -3
        }
      }
    }
  );

  const updatedDocument = await collection.findOne({ _id: 1 });
  console.log(updatedDocument);

  await client.close();
}

updateDocument();
```

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

```
from pymongo import MongoClient

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

    collection.update_one(
        {'_id': 1},
        {
            '$push': {
                'scores': {
                    '$each': [92, 88],
                    '$slice': -3
                }
            }
        }
    )

    updated_document = collection.find_one({'_id': 1})
    print(updated_document)

    client.close()

update_document()
```

------