$[<identifier>] - Amazon DocumentDB

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

$[<identifier>]

$[<identifier>] フィルタリングされた位置演算子は、指定されたフィルター条件に一致するすべての配列要素を更新します。これは、配列要素を選択的に更新する arrayFiltersオプションとともに使用されます。

パラメータ

  • field.$[identifier]: フィルタリングされた位置演算子を持つ配列フィールド。

  • arrayFilters: 更新する要素を決定するフィルター条件の配列。

例 (MongoDB シェル)

次の例は、 $[<identifier>]演算子を使用して、条件に基づいて特定の配列要素を更新する方法を示しています。

サンプルドキュメントを作成する

db.students.insertOne({ _id: 1, name: "Alice", grades: [ { subject: "Math", score: 85 }, { subject: "Science", score: 92 }, { subject: "History", score: 78 } ] });

クエリの例

db.students.updateOne( { _id: 1 }, { $inc: { "grades.$[elem].score": 5 } }, { arrayFilters: [{ "elem.score": { $gte: 80 } }] } );

出力

{ "_id" : 1, "name" : "Alice", "grades" : [ { "subject" : "Math", "score" : 90 }, { "subject" : "Science", "score" : 97 }, { "subject" : "History", "score" : 78 } ] }

コードの例

$[<identifier>] 演算子を使用するコード例を表示するには、使用する言語のタブを選択します。

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 }, { $inc: { "grades.$[elem].score": 5 } }, { arrayFilters: [{ "elem.score": { $gte: 80 } }] } ); 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}, {'$inc': {'grades.$[elem].score': 5}}, array_filters=[{'elem.score': {'$gte': 80}}] ) updated_document = collection.find_one({'_id': 1}) print(updated_document) client.close() update_document()