

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# \$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` 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()
```

------