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

MongoDB 컬렉션에서 문서를 삭제하는 방법 – remove() 메서드 완벽 가이드

MongoDB 컬렉션에서 문서를 삭제하는 방법

MongoDB에서 컬렉션(collection)에 저장된 문서(document)를 삭제하려면 remove() 메서드를 사용합니다. 기본 문법은 다음과 같습니다.

db.yourCollectionName.remove(yourDeleteValue);

이번 글에서는 실제 예제를 통해 단일 문서 삭제전체 문서 삭제 방법을 단계별로 살펴보겠습니다.

1단계: 샘플 컬렉션 생성하기

먼저 실습용으로 여러 개의 문서가 담긴 컬렉션을 만들어 보겠습니다. 아래 쿼리를 순서대로 실행합니다.

> db.deleteDocuments.insert({"UserId":1,"UserName":"Bob","UserTechnicalSubject":"Introduction to PL/SQL"});
WriteResult({ "nInserted" : 1 })

> db.deleteDocuments.insert({"UserId":2,"UserName":"Carol","UserTechnicalSubject":"Introduction to MongoDB"});
WriteResult({ "nInserted" : 1 })

> db.deleteDocuments.insert({"UserId":3,"UserName":"John","UserTechnicalSubject":"Introduction to MySQL"});
WriteResult({ "nInserted" : 1 })

> db.deleteDocuments.insert({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"});
WriteResult({ "nInserted" : 1 })

네 개의 문서가 성공적으로 삽입되었습니다.

2단계: 저장된 문서 확인하기

find() 명령어를 사용하면 생성한 컬렉션의 모든 문서를 조회할 수 있습니다.

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

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

{
    "_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"),
    "UserId" : 1,
    "UserName" : "Bob",
    "UserTechnicalSubject" : "Introduction to PL/SQL"
}
{
    "_id" : ObjectId("5c6aaab464f3d70fcc914800"),
    "UserId" : 2,
    "UserName" : "Carol",
    "UserTechnicalSubject" : "Introduction to MongoDB"
}
{
    "_id" : ObjectId("5c6aaac764f3d70fcc914801"),
    "UserId" : 3,
    "UserName" : "John",
    "UserTechnicalSubject" : "Introduction to MySQL"
}
{
    "_id" : ObjectId("5c6aaadc64f3d70fcc914802"),
    "UserId" : 4,
    "UserName" : "Maxwell",
    "UserTechnicalSubject" : "Introduction to SQL Server"
}

3단계: 단일 문서 삭제하기

컬렉션에서 특정 문서 하나만 삭제하려면 remove() 메서드에 삭제 조건을 전달하면 됩니다. 예를 들어 UserId가 4인 문서(Maxwell)를 삭제해 보겠습니다.

> db.deleteDocuments.remove({"UserId":4,"UserName":"Maxwell","UserTechnicalSubject":"Introduction to SQL Server"});
WriteResult({ "nRemoved" : 1 })

삭제가 정상적으로 처리되었는지 확인하려면 다시 find() 명령어로 전체 문서를 조회합니다.

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

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

{
    "_id" : ObjectId("5c6aaa9e64f3d70fcc9147ff"),
    "UserId" : 1,
    "UserName" : "Bob",
    "UserTechnicalSubject" : "Introduction to PL/SQL"
}
{
    "_id" : ObjectId("5c6aaab464f3d70fcc914800"),
    "UserId" : 2,
    "UserName" : "Carol",
    "UserTechnicalSubject" : "Introduction to MongoDB"
}
{
    "_id" : ObjectId("5c6aaac764f3d70fcc914801"),
    "UserId" : 3,
    "UserName" : "John",
    "UserTechnicalSubject" : "Introduction to MySQL"
}

UserId가 4였던 Maxwell의 문서가 사라진 것을 확인할 수 있습니다.

4단계: 전체 문서 삭제하기

컬렉션의 모든 문서를 한 번에 삭제하려면 조건 자리에 빈 객체({})를 넣으면 됩니다.

db.yourCollectionName.remove({ });

실제 실행 예시는 다음과 같습니다.

> db.deleteDocuments.remove({});
WriteResult({ "nRemoved" : 3 })

이렇게 하면 'deleteDocuments' 컬렉션에 남아 있던 세 개의 문서가 모두 삭제됩니다.

참고: 최신 MongoDB 버전에서는?

remove() 메서드는 MongoDB 3.2부터 공식적으로 지원 중단(deprecated) 상태입니다. 최신 버전에서는 용도에 따라 다음 메서드를 사용하는 것이 권장됩니다.

  • deleteOne(filter) – 조건에 맞는 첫 번째 문서 하나만 삭제
  • deleteMany(filter) – 조건에 맞는 모든 문서 삭제
  • deleteMany({}) – 컬렉션의 전체 문서 삭제

예를 들어 위 예제를 최신 문법으로 바꾸면 다음과 같습니다.

// 단일 문서 삭제
db.deleteDocuments.deleteOne({"UserId":4});

// 전체 문서 삭제
db.deleteDocuments.deleteMany({});

기존 코드 유지보수 시에는 remove()도 동작하지만, 새 프로젝트에서는 deleteOne()과 deleteMany()를 사용하는 것이 좋습니다.