MongoDB에서 배열 형태로 저장된 JSON 데이터의 특정 키 값을 수정해야 하는 경우가 종종 있습니다. 이 글에서는 findOne()으로 문서를 조회한 뒤 forEach()로 배열 요소를 순회하며 값을 변경하고, $set 연산자를 통해 다시 저장하는 방법을 단계별로 살펴봅니다.
1단계: 문서가 포함된 컬렉션 생성
먼저 학생 정보를 담은 StudentDetails 배열을 포함하는 문서로 컬렉션을 생성해 보겠습니다.
> db.updateListOfKeyValuesDemo.insertOne( { "StudentDetails":[ { "StudentName":"John", "StudentAge":23, "StudentCountryName":"US" }, { "StudentName":"Carol", "StudentAge":24, "StudentCountryName":"UK" }, { "StudentName":"Bob", "StudentAge":22, "StudentCountryName":"AUS" } ] } );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b5b759882024390176545")
}2단계: 저장된 문서 확인
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.
> db.updateListOfKeyValuesDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5c9b5b759882024390176545"),
"StudentDetails" : [
{
"StudentName" : "John",
"StudentAge" : 23,
"StudentCountryName" : "US"
},
{
"StudentName" : "Carol",
"StudentAge" : 24,
"StudentCountryName" : "UK"
},
{
"StudentName" : "Bob",
"StudentAge" : 22,
"StudentCountryName" : "AUS"
}
]
}3단계: JSON 배열 내 키 값 업데이트
배열 내 각 요소의 키 값을 수정하려면 먼저 findOne()으로 해당 문서를 가져온 후, forEach()로 배열을 순회하며 값을 변경하고, 변경된 문서를 $set 연산자로 다시 저장하면 됩니다.
> var documentFromCollection = db.updateListOfKeyValuesDemo.findOne({
... "_id": ObjectId("5c9b5b759882024390176545")
... });
>
> documentFromCollection.StudentDetails.forEach(function(updateStudent) {
... updateStudent.StudentName = "Ramit";
... });
> db.updateListOfKeyValuesDemo.update(
... { "_id": documentFromCollection._id },
... { "$set": { "StudentDetails": documentFromCollection.StudentDetails } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })쿼리가 정상적으로 실행되면 nMatched : 1, nModified : 1이 반환되어 하나의 문서가 성공적으로 수정되었음을 확인할 수 있습니다.
4단계: 업데이트 결과 검증
키 값이 실제로 변경되었는지 다시 한번 조회해 보겠습니다.
> db.updateListOfKeyValuesDemo.find().pretty();
실행 결과를 보면 세 명의 학생 이름이 모두 Ramit으로 변경된 것을 확인할 수 있습니다.
{
"_id" : ObjectId("5c9b5b759882024390176545"),
"StudentDetails" : [
{
"StudentName" : "Ramit",
"StudentAge" : 23,
"StudentCountryName" : "US"
},
{
"StudentName" : "Ramit",
"StudentAge" : 24,
"StudentCountryName" : "UK"
},
{
"StudentName" : "Ramit",
"StudentAge" : 22,
"StudentCountryName" : "AUS"
}
]
}참고 사항
MongoDB 3.2 이상 버전에서는 기존의 update() 대신 updateOne() 또는 updateMany() 사용이 권장됩니다. 위 예제를 최신 버전에 맞게 작성하려면 다음과 같이 변경하면 됩니다.
db.updateListOfKeyValuesDemo.updateOne(
{ "_id": documentFromCollection._id },
{ "$set": { "StudentDetails": documentFromCollection.StudentDetails } }
);
이처럼 findOne()과 forEach()를 조합하면 배열 내 여러 요소의 키 값을 손쉽게 일괄 수정할 수 있으며, 조건문을 추가하면 특정 요소만 선택적으로 변경하는 것도 가능합니다.