MongoDB에서 배열 안에 포함된 문서(하위 도큐먼트)를 삭제하려면 update 명령과 함께 $pull 연산자를 사용해야 합니다. 이 글에서는 실제 예제를 통해 단계별로 삭제 과정을 살펴보겠습니다.
1. 샘플 컬렉션 생성
먼저 문서가 담긴 컬렉션을 생성합니다. 다음 쿼리를 실행하세요.
> db.deleteDocumentsDemo.insertOne(
... {
... "_id":100,
... "StudentsDetails" : [
... {
... "StudentId" : 1,
... "StudentName" : "John"
... },
... {
... "StudentId" : 2,
... "StudentName" : "Carol"
... },
... {
... "StudentId" : 3,
... "StudentName" : "Sam"
... },
... {
... "StudentId" : 4,
... "StudentName" : "Mike"
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 100 }
> db.deleteDocumentsDemo.insertOne(
... {
... "_id":200,
... "StudentsDetails" : [
... {
... "StudentId" : 5,
... "StudentName" : "David"
... },
... {
... "StudentId" : 6,
... "StudentName" : "Ramit"
... },
... {
... "StudentId" : 7,
... "StudentName" : "Adam"
... },
... {
... "StudentId" : 8,
... "StudentName" : "Larry"
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 200 }2. 저장된 전체 문서 확인
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.
> db.deleteDocumentsDemo.find().pretty();
위 쿼리는 다음과 같은 결과를 출력합니다.
{
"_id" : 100,
"StudentsDetails" : [
{
"StudentId" : 1,
"StudentName" : "John"
},
{
"StudentId" : 2,
"StudentName" : "Carol"
},
{
"StudentId" : 3,
"StudentName" : "Sam"
},
{
"StudentId" : 4,
"StudentName" : "Mike"
}
]
}
{
"_id" : 200,
"StudentsDetails" : [
{
"StudentId" : 5,
"StudentName" : "David"
},
{
"StudentId" : 6,
"StudentName" : "Ramit"
},
{
"StudentId" : 7,
"StudentName" : "Adam"
},
{
"StudentId" : 8,
"StudentName" : "Larry"
}
]
}3. $pull 연산자로 배열 내 문서 삭제하기
이제 배열 안에 있는 특정 문서를 삭제하는 쿼리입니다. 조건으로 빈 객체({})를 지정하고 {multi: true} 옵션을 추가하면 모든 문서에 대해 업데이트가 적용됩니다.
> db.deleteDocumentsDemo.update({},
... {$pull: {StudentsDetails: {StudentName: "David"}}},
... {multi: true});
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 1 })4. 삭제 결과 검증
문서가 실제로 삭제되었는지 확인해 보겠습니다. 다시 find() 메서드를 실행합니다.
> db.deleteDocumentsDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : 100,
"StudentsDetails" : [
{
"StudentId" : 1,
"StudentName" : "John"
},
{
"StudentId" : 2,
"StudentName" : "Carol"
},
{
"StudentId" : 3,
"StudentName" : "Sam"
},
{
"StudentId" : 4,
"StudentName" : "Mike"
}
]
}
{
"_id" : 200,
"StudentsDetails" : [
{
"StudentId" : 6,
"StudentName" : "Ramit"
},
{
"StudentId" : 7,
"StudentName" : "Adam"
},
{
"StudentId" : 8,
"StudentName" : "Larry"
}
]
}결과 분석
위 출력 결과를 보면 StudentId가 5인, 즉 StudentName이 "David"인 하위 문서가 StudentsDetails 배열에서 성공적으로 제거된 것을 확인할 수 있습니다. 이처럼 $pull 연산자는 조건과 일치하는 배열 요소만 골라서 삭제할 때 매우 유용하게 사용됩니다.