$pop - Amazon DocumentDB

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

$pop

$popOperator di Amazon DocumentDB digunakan untuk menghapus elemen pertama atau terakhir dari bidang array. Ini sangat berguna ketika Anda perlu mempertahankan array ukuran tetap atau menerapkan struktur data seperti antrian dalam dokumen.

Parameter

  • field: Nama bidang array untuk menghapus elemen dari.

  • value: Nilai integer yang menentukan posisi elemen untuk menghapus. Nilai 1 menghapus elemen terakhir, sementara nilai -1 menghapus elemen pertama.

Contoh (MongoDB Shell)

Contoh ini menunjukkan bagaimana menggunakan $pop operator untuk menghapus elemen pertama dan terakhir dari bidang array.

Buat dokumen sampel

db.users.insertMany([ { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming", "hiking"] }, { "_id": 2, "name": "Jane Smith", "hobbies": ["cooking", "gardening", "painting"] } ])

Contoh kueri

// Remove the first element from the "hobbies" array db.users.update({ "_id": 1 }, { $pop: { "hobbies": -1 } }) // Remove the last element from the "hobbies" array db.users.update({ "_id": 2 }, { $pop: { "hobbies": 1 } })

Keluaran

{ "_id" : 1, "name" : "John Doe", "hobbies" : [ "swimming", "hiking" ] } { "_id" : 2, "name" : "Jane Smith", "hobbies" : [ "cooking", "gardening" ] }

Contoh kode

Untuk melihat contoh kode untuk menggunakan $pop 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('users'); // Remove the first element from the "hobbies" array await collection.updateOne({ "_id": 1 }, { $pop: { "hobbies": -1 } }); // Remove the last element from the "hobbies" array await collection.updateOne({ "_id": 2 }, { $pop: { "hobbies": 1 } }); const users = await collection.find().toArray(); console.log(users); 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['users'] # Remove the first element from the "hobbies" array collection.update_one({"_id": 1}, {"$pop": {"hobbies": -1}}) # Remove the last element from the "hobbies" array collection.update_one({"_id": 2}, {"$pop": {"hobbies": 1}}) users = list(collection.find()) print(users) client.close() example()