문서 삭제
개요
이 가이드에서는 MongoDB Java 드라이버로 문서를 제거하는 방법에 대해 알아볼 수 있습니다.
쿼리 필터를 deleteOne()
, deleteMany()
또는 findOneAndDelete()
메서드에 전달하여 문서를 제거할 수 있습니다.
deleteOne()
메서드는 단일 문서를 삭제합니다. 쿼리 필터가 두 개 이상의 문서와 일치하는 경우 메서드는 collection에서 처음 일치하는 항목을 제거합니다.
deleteMany()
메서드는 쿼리 필터와 일치하는 모든 문서를 삭제합니다.
findOneAndDelete()
메서드는 collection에서 처음 일치하는 항목을 원자 단위로 찾아서 삭제합니다.
인덱스를 데이터 정렬 또는 힌트로 지정하려면 deleteOne()
및 deleteMany()
메서드에 대한 두 번째 매개변수로 DeleteOptions
을 사용합니다.
데이터 정렬을 지정하거나, 인덱스에 힌트를 제공하거나, 정렬 순서를 지정하거나, 반환된 문서에 프로젝션을 지정하려면 findOneAndDelete()
메서드의 두 번째 매개변수로 FindOneAndDeleteOptions
를 사용합니다.
샘플 문서
다음 예는 8가지 색상의 페인트를 판매하는 페인트 가게에 관한 예입니다. 이 스토어는 연례 온라인 판매를 통해 paint_inventory
collection에 다음 문서를 포함시켰습니다.
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 2, "color": "purple", "qty": 8 } { "_id": 3, "color": "blue", "qty": 0 } { "_id": 4, "color": "white", "qty": 0 } { "_id": 5, "color": "yellow", "qty": 6 } { "_id": 6, "color": "pink", "qty": 0 } { "_id": 7, "color": "green", "qty": 0 } { "_id": 8, "color": "black", "qty": 8 }
복수의 문서 삭제
페인트 매장 웹사이트에는 paint_inventory
collection의 모든 문서가 표시됩니다. 매장에서는 고객의 혼동을 줄이기 위해 재고가 없는 색상을 제거하려고 합니다.
재고가 없는 색상을 제거하려면 qty
이 0
인 paint_inventory
컬렉션을 쿼리하고 쿼리를 deleteMany()
메서드에 전달합니다.
Bson filter = Filters.eq("qty", 0); collection.deleteMany(filter);
다음은 paint_inventory
collection에 남아 있는 문서를 보여줍니다.
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 2, "color": "purple", "qty": 8 } { "_id": 5, "color": "yellow", "qty": 6 } { "_id": 8, "color": "black", "qty": 8 }
문서 삭제
이 가게는 남은 노란색 페인트 수량을 기부합니다. 즉, 노란색의 qty
는 이제 0
이며 collection에서 노란색을 제거해야 합니다.
노란색을 제거하려면 color
가 "yellow"
인 paint_inventory
컬렉션을 쿼리하고 deleteOne()
메서드에 쿼리를 전달합니다.
Bson filter = Filters.eq("color", "yellow"); collection.deleteOne(filter);
다음은 paint_inventory
collection에 남아 있는 문서를 보여줍니다.
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 2, "color": "purple", "qty": 8 } { "_id": 8, "color": "black", "qty": 8 }
문서 찾기 및 삭제
상점에서는 나머지 수량의 자주색 페인트를 뽑고 paint_inventory
collection에서 자주색을 제거하려고 합니다.
색상을 선택하려면 color
이 "purple"
인 paint_inventory
collection을 쿼리하고 쿼리를 findOneAndDelete()
메서드에 전달합니다.
Bson filter = Filters.eq("color", "purple"); System.out.println(collection.findOneAndDelete(filter).toJson());
다른 삭제 메서드와 달리 findOneAndDelete()
은 삭제된 문서를 반환합니다.
{ "_id": 2, "color": "purple", "qty": 8 }
참고
쿼리 필터와 일치하는 문서가 없으면 문서가 삭제되지 않고 메서드는 null
을(를) 반환합니다.
다음은 paint_inventory
collection에 남아 있는 문서를 보여줍니다.
{ "_id": 1, "color": "red", "qty": 5 } { "_id": 8, "color": "black", "qty": 8 }
삭제 예시: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스 에 연결하는 방법에 대해 자세히 학습 MongoClient 만들기 가이드 참조하세요. 이 예시 movies
sample_mflix
Atlas 샘플 데이터 세트에 포함된 데이터베이스 의 컬렉션 도 사용합니다. Atlas 시작하기가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.
다음 코드는 하나의 삭제 작업과 다수 삭제 작업을 수행하는 완전한 독립형 파일 입니다.
// Deletes documents from a collection by using the Java driver package org.example; import static com.mongodb.client.model.Filters.eq; import org.bson.Document; import org.bson.conversions.Bson; import com.mongodb.MongoException; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.result.DeleteResult; import static com.mongodb.client.model.Filters.lt; public class Delete { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); Bson deleteOneQuery = eq("title", "The Garbage Pail Kids Movie"); // Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie" DeleteResult result = collection.deleteOne(deleteOneQuery); System.out.println("Deleted document count - delete one: " + result.getDeletedCount()); Bson deleteManyQuery = lt("imdb.rating", 1.9); // Deletes all documents that have an "imdb.rating" value less than 1.9 result = collection.deleteMany(deleteManyQuery); // Prints the number of deleted documents System.out.println("Deleted document count - delete many: " + result.getDeletedCount()); } } }
Deleted document count - query for one: 1 Deleted document count - unlimited query: 4
이 예제의 쿼리는 eq()
및 lt()
필터를 사용하여 문서를 쿼리 . 필터에 대한 자세한 내용은 필터 클래스 API 문서를 참조하세요.
추가 정보
API 문서
문서를 삭제 데 사용되는 메서드 및 클래스에 대한 자세한 내용은 다음 API 설명서를 참조하세요.