

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

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

`$slice` 射影演算子は、クエリ結果で返される配列要素の数を制限します。これにより、配列全体をロードすることなく、配列フィールドの先頭または末尾から特定の数の要素を取得できます。

**パラメータ**
+ `field`: 射影する配列フィールド。
+ `count`: 返される要素の数。正の値は最初から要素を返し、最後に負の値を返します。

## 例 (MongoDB シェル)
<a name="slice-projection-examples"></a>

次の例は、`$slice`射影演算子を使用して配列フィールドから最初の 2 つの項目のみを返す方法を示しています。

**サンプルドキュメントを作成する**

```
db.inventory.insertMany([
  { _id: 1, item: "notebook", tags: ["office", "school", "supplies", "writing"] },
  { _id: 2, item: "pen", tags: ["office", "writing"] },
  { _id: 3, item: "folder", tags: ["office", "supplies", "storage", "organization"] }
]);
```

**クエリの例**

```
db.inventory.find(
  {},
  { item: 1, tags: { $slice: 2 } }
)
```

**出力**

```
{ "_id" : 1, "item" : "notebook", "tags" : [ "office", "school" ] }
{ "_id" : 2, "item" : "pen", "tags" : [ "office", "writing" ] }
{ "_id" : 3, "item" : "folder", "tags" : [ "office", "supplies" ] }
```

## コードの例
<a name="slice-projection-code"></a>

`$slice` 射影演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

------
#### [ 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('inventory');

  const result = await collection.find(
    {},
    { projection: { item: 1, tags: { $slice: 2 } } }
  ).toArray();

  console.log(JSON.stringify(result, null, 2));
  await 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['test']
    collection = db['inventory']

    result = list(collection.find(
        {},
        {'item': 1, 'tags': {'$slice': 2}}
    ))

    print(result)
    client.close()

example()
```

------