

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

# \$1size
<a name="size-query"></a>

Operator `$size` kueri cocok dengan dokumen di mana bidang array memiliki persis jumlah elemen yang ditentukan. Ini berguna untuk memfilter dokumen berdasarkan panjang array.

**Parameter**
+ `field`: Bidang array untuk memeriksa.
+ `count`: Jumlah pasti elemen array harus berisi.

## Contoh (MongoDB Shell)
<a name="size-query-examples"></a>

Contoh berikut menunjukkan menggunakan `$size` operator untuk menemukan semua produk yang memiliki tepat tiga tag.

**Buat dokumen sampel**

```
db.products.insertMany([
  { _id: 1, name: "Laptop", tags: ["electronics", "computers", "portable"] },
  { _id: 2, name: "Mouse", tags: ["electronics", "accessories"] },
  { _id: 3, name: "Desk", tags: ["furniture", "office", "workspace"] },
  { _id: 4, name: "Monitor", tags: ["electronics"] }
]);
```

**Contoh kueri**

```
db.products.find({ tags: { $size: 3 } });
```

**Keluaran**

```
{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] }
{ "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }
```

## Contoh kode
<a name="size-query-code"></a>

Untuk melihat contoh kode untuk menggunakan operator `$size` kueri, 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('products');

  const result = await collection.find({ tags: { $size: 3 } }).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['products']

    result = list(collection.find({'tags': {'$size': 3}}))

    print(result)
    client.close()

example()
```

------