本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$[<identifier>]
$[<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()