MongoDB에서 배열에 담긴 모든 요소를 조건 없이 한꺼번에 제거하고 싶다면 $set 연산자를 사용하면 됩니다. $set 연산자는 특정 필드의 값을 새로운 값으로 대체하는 역할을 하며, 배열 필드에 빈 배열([])을 할당하면 기존 요소들이 모두 사라지고 빈 배열만 남게 됩니다.
이 글에서는 실제 예제를 통해 컬렉션 생성부터 배열 전체 삭제, 그리고 결과 확인까지 단계별로 살펴보겠습니다.
1. 샘플 컬렉션 생성하기
먼저 insertOne() 메서드를 사용해 학생 정보가 담긴 문서 두 개를 가진 컬렉션을 생성합니다.
> db.pullAllElementDemo.insertOne(
... {
... "StudentId": 101,
... "StudentDetails": [
... {
... "StudentName": "Carol",
... "StudentAge": 21,
... "StudentCountryName": "US"
... },
... {
... "StudentName": "Chris",
... "StudentAge": 24,
... "StudentCountryName": "AUS"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdd9c8685b30d09a7111e4")
}> db.pullAllElementDemo.insertOne(
... {
... "StudentId": 102,
... "StudentDetails": [
... {
... "StudentName": "Robert",
... "StudentAge": 27,
... "StudentCountryName": "UK"
... },
... {
... "StudentName": "David",
... "StudentAge": 23,
... "StudentCountryName": "US"
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5ccdd9f7685b30d09a7111e5")
}2. 저장된 문서 확인하기
find() 메서드로 컬렉션의 모든 문서를 조회해 보겠습니다.
> db.pullAllElementDemo.find().pretty();
실행하면 다음과 같은 출력 결과를 확인할 수 있습니다.
{
"_id" : ObjectId("5ccdd9c8685b30d09a7111e4"),
"StudentId" : 101,
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
]
}
{
"_id" : ObjectId("5ccdd9f7685b30d09a7111e5"),
"StudentId" : 102,
"StudentDetails" : [
{
"StudentName" : "Robert",
"StudentAge" : 27,
"StudentCountryName" : "UK"
},
{
"StudentName" : "David",
"StudentAge" : 23,
"StudentCountryName" : "US"
}
]
}3. $set으로 배열 전체 비우기
이제 핵심 단계입니다. update() 메서드와 함께 $set 연산자를 사용하여 StudentId가 102인 문서의 StudentDetails 배열을 빈 배열로 대체합니다. 이렇게 하면 별도의 조건 없이도 배열의 모든 요소가 한 번에 제거됩니다.
> db.pullAllElementDemo.update(
... { StudentId: 102 },
... { "$set": { "StudentDetails": [] } }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })실행 결과에서 nModified: 1이 반환되었으므로, 하나의 문서가 성공적으로 수정된 것을 알 수 있습니다.
4. 변경 결과 검증하기
수정이 정상적으로 적용되었는지 다시 전체 문서를 조회해 확인해 보겠습니다.
> db.pullAllElementDemo.find().pretty();
{
"_id" : ObjectId("5ccdd9c8685b30d09a7111e4"),
"StudentId" : 101,
"StudentDetails" : [
{
"StudentName" : "Carol",
"StudentAge" : 21,
"StudentCountryName" : "US"
},
{
"StudentName" : "Chris",
"StudentAge" : 24,
"StudentCountryName" : "AUS"
}
]
}
{
"_id" : ObjectId("5ccdd9f7685b30d09a7111e5"),
"StudentId" : 102,
"StudentDetails" : [ ]
}출력 결과를 보면 StudentId가 102인 문서의 StudentDetails 배열이 완전히 비워진 것을 확인할 수 있습니다. 반면 StudentId가 101인 문서는 그대로 유지됩니다.
정리 및 참고 사항
- $set 연산자: 필드 값을 통째로 교체하므로, 빈 배열([])을 지정하면 기존 배열 요소가 모두 제거됩니다.
- $pullAll과의 차이:
$pullAll은 지정한 값과 일치하는 요소만 제거하지만, $set은 조건 없이 배열 전체를 새 값으로 덮어씁니다. - updateOne 권장: 최신 MongoDB 버전에서는 deprecated된
update()대신updateOne()또는updateMany()사용을 권장합니다.