翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
$[]
$[] すべての位置演算子は、配列内のすべての要素を更新します。これは、配列フィールドのすべての要素を変更する必要がある場合に使用されます。
パラメータ
例 (MongoDB シェル)
次の例は、 $[]演算子を使用してすべての配列要素を更新する方法を示しています。
サンプルドキュメントを作成する
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()