$slice - Amazon DocumentDB

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

$slice

Operator $slice agregasi memungkinkan Anda mengembalikan subset array dengan melintasi array dari awal atau akhir array. Ini digunakan untuk menampilkan sejumlah item terbatas dari bidang array, seperti item N atas atau bawah.

Parameter

  • array: Bidang array yang akan diiris.

  • n: Sebuah integer yang menentukan jumlah elemen untuk kembali. Nilai positif dimulai dari awal array, sedangkan nilai negatif dimulai dari akhir array.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan $slice untuk mengembalikan dua permen favorit pertama untuk setiap koki.

Buat dokumen sampel

db.sweets.insertMany([ { "_id" : 1, "name" : "Alvin", "favorites": [ "chocolate", "cake", "toffee", "beignets" ] }, { "_id" : 2, "name" : "Tom", "favorites": [ "donuts", "pudding", "pie" ] }, { "_id" : 3, "name" : "Jessica", "favorites": [ "fudge", "smores", "pudding", "cupcakes" ] }, { "_id" : 4, "name" : "Rachel", "favorites": [ "ice cream" ] } ]);

Contoh kueri

db.sweets.aggregate([ { $project: { _id: 0, name: 1, topTwoFavorites: { $slice: [ "$favorites", 2 ] } } } ]);

Keluaran

[ { name: 'Alvin', topTwoFavorites: [ 'chocolate', 'cake' ] }, { name: 'Tom', topTwoFavorites: [ 'donuts', 'pudding' ] }, { name: 'Jessica', topTwoFavorites: [ 'fudge', 'smores' ] }, { name: 'Rachel', topTwoFavorites: [ 'ice cream' ] } ]

Dalam contoh ini, $slice operator digunakan untuk mengekstrak dua elemen pertama dari favorites array untuk setiap dokumen.

Contoh kode

Untuk melihat contoh kode untuk menggunakan $slice perintah, 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('sweets'); const result = await collection.aggregate([ { $project: { name: 1, topTwoFavorites: { $slice: ['$favorites', 2] } } } ]).toArray(); console.log(result); 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['sweets'] result = list(collection.aggregate([ { '$project': { 'name': 1, 'topTwoFavorites': { '$slice': ['$favorites', 2] } } } ])) print(result) client.close() example()