Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 자식 객체 업데이트하는 방법 – $set 연산자 완벽 가이드

MongoDB에서 자식 객체를 업데이트하는 방법

MongoDB에서 문서 내부에 중첩된 자식 객체(child object)의 특정 필드를 수정할 때는 $set 연산자를 사용합니다. 점 표기법(dot notation)을 함께 활용하면 상위 문서 전체를 교체하지 않고도 원하는 하위 필드만 정확하게 갱신할 수 있습니다. 아래 예제를 통해 단계별로 살펴보겠습니다.

1단계: 컬렉션 생성 및 문서 삽입

먼저 insertOne() 메서드로 컬렉션을 생성하고 샘플 문서를 하나 삽입합니다.

> db.updateChildObjectsDemo.insertOne({"StudentName":"Chris","StudentOtherDetails":{"StudentSubject":"MongoDB","StudentCountryName":"AUS"}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ce964e078f00858fb12e91f")
}

2단계: 저장된 문서 조회

find() 메서드에 pretty()를 함께 사용하면 컬렉션의 모든 문서를 읽기 쉬운 형태로 확인할 수 있습니다.

> db.updateChildObjectsDemo.find().pretty();

실행 결과는 다음과 같습니다.

{
   "_id" : ObjectId("5ce964e078f00858fb12e91f"),
   "StudentName" : "Chris",
   "StudentOtherDetails" : {
      "StudentSubject" : "MongoDB",
      "StudentCountryName" : "AUS"
   }
}

3단계: $set 연산자로 자식 객체 업데이트

이제 update() 메서드에 $set 연산자를 적용하여 StudentOtherDetails 객체 안의 StudentCountryName 필드만 변경해 보겠습니다. 핵심은 "StudentOtherDetails.StudentCountryName"처럼 점 표기법으로 경로를 지정하는 것입니다.

> db.updateChildObjectsDemo.update({"StudentName" : "Chris"},{$set:{"StudentOtherDetails.StudentCountryName":"UK"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

4단계: 업데이트 결과 확인

문서를 다시 조회하면 다른 값들은 그대로 유지된 채 국가명만 UK로 변경된 것을 확인할 수 있습니다.

> db.updateChildObjectsDemo.find().pretty();
{
   "_id" : ObjectId("5ce964e078f00858fb12e91f"),
   "StudentName" : "Chris",
   "StudentOtherDetails" : {
      "StudentSubject" : "MongoDB",
      "StudentCountryName" : "UK"
   }
}

핵심 정리

  • 중첩된 필드를 수정할 때는 $set 연산자 + 점 표기법 조합을 사용합니다.
  • WriteResult의 nMatched는 조건에 일치한 문서 수, nModified는 실제로 변경된 문서 수를 의미합니다.
  • 최신 MongoDB 버전에서는 deprecated된 update() 대신 updateOne(), updateMany() 사용이 권장됩니다.