이를 위해 위치 연산자 $를 사용할 수 있습니다. 위의 개념을 이해하기 위해 문서로 컬렉션을 만들어 보겠습니다. 문서로 컬렉션을 생성하는 쿼리는 다음과 같습니다 -
> db.incrementValueInNestedArrayDemo.insertOne(
... {"UniqueId":1,
... "StudentDetails":
... [
... {
... "StudentId":101,
... "StudentMarks":97
... },
... {
... "StudentId":103,
... "StudentMarks":99
... },
... {
... "StudentId":105,
... "StudentMarks":69
... },
... {
... "StudentId":107,
... "StudentMarks":59
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c77dd71fc4e719b197a12f7")
} find() 메서드를 사용하여 컬렉션의 모든 문서를 표시합니다. 쿼리는 다음과 같습니다 -
> db.incrementValueInNestedArrayDemo.find().pretty();
다음은 출력입니다 -
{
"_id" : ObjectId("5c77dd71fc4e719b197a12f7"),
"UniqueId" : 1,
"StudentDetails" : [
{
"StudentId" : 101,
"StudentMarks" : 97
},
{
"StudentId" : 103,
"StudentMarks" : 99
},
{
"StudentId" : 105,
"StudentMarks" : 92
},
{
"StudentId" : 107,
"StudentMarks" : 59
}
]
} 다음은 중첩 배열의 값을 증가시키는 쿼리입니다 -
> db.incrementValueInNestedArrayDemo.update({UniqueId:1,"StudentDetails.StudentId":107},
{$inc:{"StudentDetails.$.StudentMarks":1}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) 중첩된 배열 값이 위의 컬렉션에서 StudentId 107 −
로 증가했는지 여부를 확인하겠습니다.> db.incrementValueInNestedArrayDemo.find().pretty();
다음은 출력입니다 -
{
"_id" : ObjectId("5c77dd71fc4e719b197a12f7"),
"UniqueId" : 1,
"StudentDetails" :
[
{
"StudentId" : 101,
"StudentMarks" : 97
},
{
"StudentId" : 103,
"StudentMarks" : 99
},
{
"StudentId" : 105,
"StudentMarks" : 92
},
{
"StudentId" : 107,
"StudentMarks" : 60
}
]
} 샘플 출력을 보면 필드 이름 "StudentMarks"가 59에서 60으로 업데이트되었으며, 이는 1씩 증가함을 의미합니다.