本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$[<identifier>]
$[<identifier>] 篩選的位置運算子會更新符合指定篩選條件的所有陣列元素。它與 arrayFilters選項搭配使用,以選擇性地更新陣列元素。
參數
範例 (MongoDB Shell)
下列範例示範如何使用 $[<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()