MongoDB 문서에 저장된 배열에서 특정 요소를 제거하려면 $pull 연산자를 사용하면 됩니다. $pull은 지정한 조건과 일치하는 값을 배열에서 모두 삭제해 주는 업데이트 연산자입니다.
$pull 연산자 기본 문법
다음은 $pull을 사용하여 배열 요소를 제거하는 기본적인 쿼리 형식입니다.
db.yourCollectionName.update( { }, { $pull: { yourFieldName: yourValue } }, { multi: true } );여기서 { multi: true } 옵션은 조건에 일치하는 모든 문서에 대해 업데이트를 적용하겠다는 의미입니다. 이 옵션을 생략하면 일치하는 첫 번째 문서만 수정됩니다.
참고: MongoDB 3.2 이상 버전에서는update()대신updateMany()사용이 권장됩니다.updateMany()는 기본적으로 여러 문서를 한 번에 수정하므로{ multi: true }옵션이 필요 없습니다.
1단계: 컬렉션 생성 및 문서 삽입
먼저 테스트용 컬렉션을 만들고 샘플 문서를 삽입해 보겠습니다.
> db.removeArrayElementsDemo.insertOne({"AllPlayerName":["John","Sam","Carol","David"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd90d011a844af18acdffc1")
}
> db.removeArrayElementsDemo.insertOne({"AllPlayerName":["Chris","Robert","John","Mike"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd90d2e1a844af18acdffc2")
}2단계: 전체 문서 조회하기
find() 메서드를 사용해 컬렉션의 모든 문서를 확인합니다.
> db.removeArrayElementsDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.
{
"_id" : ObjectId("5cd90d011a844af18acdffc1"),
"AllPlayerName" : [
"John",
"Sam",
"Carol",
"David"
]
}
{
"_id" : ObjectId("5cd90d2e1a844af18acdffc2"),
"AllPlayerName" : [
"Chris",
"Robert",
"John",
"Mike"
]
}두 문서 모두 AllPlayerName 배열 안에 "John"이라는 값이 포함되어 있는 것을 확인할 수 있습니다.
3단계: $pull로 배열 요소 제거하기
이제 $pull 연산자를 사용해 두 문서에서 "John"을 모두 제거해 보겠습니다.
> db.removeArrayElementsDemo.update( { }, { $pull: { AllPlayerName: "John" } }, { multi: true } );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })실행 결과를 살펴보면 nMatched: 2, nModified: 2로 표시되는데, 이는 두 개의 문서가 조건에 일치했고 두 문서 모두 성공적으로 수정되었음을 의미합니다.
4단계: 최종 결과 확인
수정이 정상적으로 적용되었는지 다시 한번 전체 문서를 조회해 보겠습니다.
> db.removeArrayElementsDemo.find().pretty();
출력 결과는 다음과 같습니다.
{
"_id" : ObjectId("5cd90d011a844af18acdffc1"),
"AllPlayerName" : [
"Sam",
"Carol",
"David"
]
}
{
"_id" : ObjectId("5cd90d2e1a844af18acdffc2"),
"AllPlayerName" : [
"Chris",
"Robert",
"Mike"
]
}두 문서의 AllPlayerName 배열에서 "John"이 모두 사라진 것을 확인할 수 있습니다.
정리
- $pull 연산자는 배열에서 지정한 값(또는 조건)과 일치하는 요소를 제거합니다.
{ multi: true }옵션을 사용하면 일치하는 모든 문서에 업데이트가 적용됩니다.- 최신 MongoDB 버전에서는
updateMany()를 사용하는 것이 좋습니다. 예:db.collection.updateMany({}, { $pull: { 필드명: 값 } })
이처럼 $pull 하나만 잘 활용해도 MongoDB 배열 데이터를 손쉽게 관리할 수 있습니다.