本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$[]
al $[] l 位置运算符更新数组中的所有元素。当你需要修改数组字段中的每个元素时,就会使用它。
参数
示例(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()