

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

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

Operator `$slice` proyeksi membatasi jumlah elemen array yang dikembalikan dalam hasil query. Ini memungkinkan Anda untuk mengambil sejumlah elemen tertentu dari awal atau akhir bidang array tanpa memuat seluruh array.

**Parameter**
+ `field`: Bidang array untuk proyek.
+ `count`: Jumlah elemen yang akan dikembalikan. Nilai positif mengembalikan elemen dari awal, nilai negatif dari akhir.

## Contoh (MongoDB Shell)
<a name="slice-projection-examples"></a>

Contoh berikut menunjukkan bagaimana menggunakan operator `$slice` proyeksi untuk mengembalikan hanya dua item pertama dari bidang array.

**Buat dokumen sampel**

```
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"] }
]);
```

**Contoh kueri**

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

**Keluaran**

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

## Contoh kode
<a name="slice-projection-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$slice` proyeksi, pilih tab untuk bahasa yang ingin Anda gunakan:

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

------