$ - Amazon DocumentDB

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

$

Operator $ posisi memperbarui elemen array pertama yang cocok dengan kondisi kueri. Ini bertindak sebagai placeholder untuk posisi elemen array yang cocok.

Parameter

  • field.$: Bidang array dengan operator posisi untuk memperbarui elemen pencocokan pertama.

Contoh (MongoDB Shell)

Contoh berikut menunjukkan menggunakan operator $ posisi untuk memperbarui elemen array tertentu.

Buat dokumen sampel

db.inventory.insertMany([ { _id: 1, item: "Widget", quantities: [10, 20, 30] }, { _id: 2, item: "Gadget", quantities: [5, 15, 25] } ]);

Contoh kueri

db.inventory.updateOne( { _id: 1, quantities: 20 }, { $set: { "quantities.$": 22 } } );

Keluaran

{ "_id" : 1, "item" : "Widget", "quantities" : [ 10, 22, 30 ] }

Contoh kode

Untuk melihat contoh kode untuk menggunakan operator $ posisi, 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('inventory'); await collection.updateOne( { _id: 1, quantities: 20 }, { $set: { "quantities.$": 22 } } ); 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.inventory collection.update_one( {'_id': 1, 'quantities': 20}, {'$set': {'quantities.$': 22}} ) updated_document = collection.find_one({'_id': 1}) print(updated_document) client.close() update_document()