MongoDB 배열에서 객체 제거하기
MongoDB에서 배열에 저장된 특정 객체를 삭제해야 할 때는 $pull 연산자를 사용하면 됩니다. $pull 연산자는 지정한 조건과 일치하는 모든 요소를 배열에서 자동으로 제거해 주는 강력한 업데이트 연산자입니다.
개념을 쉽게 이해할 수 있도록, 실제 예제 문서를 담은 컬렉션을 만들어 단계별로 살펴보겠습니다.
1단계: 샘플 컬렉션 생성
먼저 학생 정보와 학술 프로젝트 배열을 포함하는 문서를 삽입합니다. 컬렉션 생성 쿼리는 다음과 같습니다.
> db.removeObjectFromArrayDemo.insertOne(
... {
... "StudentName": "John",
... "StudentAcademicProjectDetails":
... [{
... "StudentProjectId": 101,
... "StudentProjectName": "Pig Dice Game"
... },
... {
... "StudentProjectId": 110,
... "StudentProjectName": "Library Management System"
... },
... {
... "StudentProjectId": 120,
... "StudentProjectName": "Phonebook Management System"
... }]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8ad13d6cea1f28b7aa0817")
}위 쿼리는 'John'이라는 학생의 세 개 프로젝트 정보를 배열 형태로 저장합니다.
2단계: 저장된 문서 확인
find() 메서드를 사용하면 컬렉션의 모든 문서를 조회할 수 있습니다.
> db.removeObjectFromArrayDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 101,
"StudentProjectName" : "Pig Dice Game"
},
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
}현재 배열에는 세 개의 프로젝트 객체가 들어 있는 것을 확인할 수 있습니다.
3단계: $pull 연산자로 객체 제거
이제 StudentProjectId가 101인 프로젝트 객체를 배열에서 제거해 보겠습니다. update() 메서드와 함께 $pull 연산자를 사용하는 쿼리는 다음과 같습니다.
> db.removeObjectFromArrayDemo.update(
... {'_id': ObjectId("5c8ad13d6cea1f28b7aa0817")},
... { $pull: { "StudentAcademicProjectDetails" : { StudentProjectId: 101 } } },
... false,
... true
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })쿼리 구조를 살펴보면 다음과 같습니다.
- 첫 번째 인수: 업데이트 대상 문서를 찾는 조건 (_id 기준)
- 두 번째 인수: $pull 연산자로 배열 필드와 제거 조건 지정
- nModified : 1: 하나의 문서가 성공적으로 수정되었음을 의미
4단계: 제거 결과 검증
객체가 실제로 배열에서 삭제되었는지 다시 한번 find() 메서드로 확인해 보겠습니다.
> db.removeObjectFromArrayDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c8ad13d6cea1f28b7aa0817"),
"StudentName" : "John",
"StudentAcademicProjectDetails" : [
{
"StudentProjectId" : 110,
"StudentProjectName" : "Library Management System"
},
{
"StudentProjectId" : 120,
"StudentProjectName" : "Phonebook Management System"
}
]
}위 출력 결과를 보면 StudentProjectId가 101인 객체가 성공적으로 제거되었고, 나머지 두 개의 프로젝트(110, 120)는 그대로 유지된 것을 확인할 수 있습니다.
정리
MongoDB에서 배열 내 객체를 삭제하는 작업은 $pull 연산자 하나로 간단하게 처리할 수 있습니다. 조건에 일치하는 요소만 정확히 골라내어 제거하기 때문에, 중첩 배열 데이터를 관리할 때 매우 유용합니다. 참고로 최신 MongoDB 버전에서는 update()보다 updateOne() 또는 updateMany() 메서드 사용이 권장됩니다.