$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 pembaruan memodifikasi array dengan membatasi ukurannya. Ketika digunakan dengan $push operator, ini membatasi jumlah elemen dalam array, hanya menyimpan jumlah tertentu dari elemen terbaru atau tertua.

Parameter

  • field: Bidang array untuk memodifikasi.

  • count: Jumlah maksimum elemen yang harus disimpan. Nilai positif menjaga elemen N pertama, nilai negatif menjaga elemen N terakhir.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan cara menggunakan operator $slice pembaruan $push untuk mempertahankan array ukuran tetap dari skor terbaru.

Buat dokumen sampel

db.students.insertOne({ _id: 1, name: "Alice", scores: [85, 90, 78] });

Contoh kueri

db.students.updateOne( { _id: 1 }, { $push: { scores: { $each: [92, 88], $slice: -3 } } } )

Keluaran

{ "_id" : 1, "name" : "Alice", "scores" : [ 78, 92, 88 ] }

Dalam contoh ini, $slice: -3 pengubah hanya menyimpan tiga elemen terakhir setelah mendorong nilai baru ke array.

Contoh kode

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

Node.js
const { MongoClient } = require('mongodb'); async function updateDocument() { 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('students'); await collection.updateOne( { _id: 1 }, { $push: { scores: { $each: [92, 88], $slice: -3 } } } ); const updatedDocument = await collection.findOne({ _id: 1 }); console.log(updatedDocument); await client.close(); } updateDocument();
Python
from pymongo import MongoClient def update_document(): 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.students collection.update_one( {'_id': 1}, { '$push': { 'scores': { '$each': [92, 88], '$slice': -3 } } } ) updated_document = collection.find_one({'_id': 1}) print(updated_document) client.close() update_document()