$isArray - Amazon DocumentDB

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

$isArray

$isArrayOperator di Amazon DocumentDB digunakan untuk memeriksa apakah bidang dalam dokumen adalah array. Operator ini dapat berguna dalam pipeline agregasi dan ekspresi bersyarat untuk menangani bidang tipe array.

Parameter

  • field: Jalur bidang untuk memeriksa apakah itu adalah array.

Contoh (MongoDB Shell)

Contoh ini menunjukkan cara menggunakan $isArray operator untuk mengidentifikasi dokumen di mana bidang “inventaris” adalah array.

Buat dokumen sampel

db.videos.insertMany([ { "_id":1, "name":"Live Soft", "inventory": {"Des Moines": 1000, "Ames" : 500}}, { "_id":2, "name":"Top Pilot", "inventory": {"Mason City": 250, "Des Moines": 1000}}, { "_id":3, "name":"Romancing the Rock", "inventory": {"Mason City": 250, "Ames" : 500}}, { "_id":4, "name":"Bravemind", "inventory": [{"location": "Mason City", "count": 250}, {"location": "Des Moines", "count": 1000}, {"location": "Ames", "count": 500}]} ]);

Contoh kueri

db.videos.aggregate([ { $match: { $isArray: "$inventory" } }, { $project: { _id: 1, name: 1, "inventory.location": 1, "inventory.count": 1 } } ]).pretty();

Keluaran

{ "_id": 4, "name": "Bravemind", "inventory": [ { "location": "Mason City", "count": 250 }, { "location": "Des Moines", "count": 1000 }, { "location": "Ames", "count": 500 } ] }

Contoh kode

Untuk melihat contoh kode untuk menggunakan $isArray perintah, pilih tab untuk bahasa yang ingin Anda gunakan:

Node.js
const { MongoClient } = require('mongodb'); async function run() { 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('videos'); const result = await collection.aggregate([ { $match: { $isArray: '$inventory' } }, { $project: { _id: 1, name: 1, "inventory.location": 1, "inventory.count": 1 } } ]).toArray(); console.log(result); await client.close(); } run();
Python
from pymongo import MongoClient 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['videos'] result = list(collection.aggregate([ { '$match': { '$isArray': '$inventory' } }, { '$project': { '_id': 1, 'name': 1, 'inventory.location': 1, 'inventory.count': 1 } } ])) print(result) client.close()