기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
$[<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()