$[] - Amazon DocumentDB

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

$[]

Operator $[] semua posisi memperbarui semua elemen dalam array. Hal ini digunakan ketika Anda perlu memodifikasi setiap elemen dalam bidang array.

Parameter

  • field.$[]: Bidang array dengan operator semua posisi untuk memperbarui semua elemen.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan menggunakan $[] operator untuk memperbarui semua elemen array.

Buat dokumen sampel

db.products.insertOne({ _id: 1, name: "Laptop", prices: [1000, 1100, 1200] });

Contoh kueri

db.products.updateOne( { _id: 1 }, { $inc: { "prices.$[]": 50 } } );

Keluaran

{ "_id" : 1, "name" : "Laptop", "prices" : [ 1050, 1150, 1250 ] }

Contoh kode

Untuk melihat contoh kode untuk menggunakan $[] operator, 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('products'); await collection.updateOne( { _id: 1 }, { $inc: { "prices.$[]": 50 } } ); 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.products collection.update_one( {'_id': 1}, {'$inc': {'prices.$[]': 50}} ) updated_document = collection.find_one({'_id': 1}) print(updated_document) client.close() update_document()