$[] - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$[]

$[] 所有位置運算子都會更新陣列中的所有元素。當您需要修改陣列欄位中的每個元素時,會使用它。

參數

  • field.$[]:具有所有位置運算子的陣列欄位,用於更新所有元素。

範例 (MongoDB Shell)

下列範例示範如何使用 $[]運算子更新所有陣列元素。

建立範例文件

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

查詢範例

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

輸出

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

程式碼範例

若要檢視使用 $[] 運算子的程式碼範例,請選擇您要使用的語言標籤:

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()