Docs Menu
Docs Home
/ / /
Java 동기화
/ /

문서 삭제

MongoCollection 객체에서 deleteOne() 메서드를 사용하여 collection에서 단일 문서를 삭제할 수 있습니다. 이 메서드는 삭제하려는 문서와 일치하는 쿼리 필터를 허용합니다. 필터를 지정하지 않으면 MongoDB는 collection의 첫 번째 문서와 일치합니다. deleteOne() 메서드는 일치하는 첫 번째 문서만 삭제합니다.

이 메서드는 작업의 결과로 삭제된 문서 수 등의 정보가 포함된 DeleteResult 인스턴스를 반환합니다.

삭제 작업이 실패하면 드라이버에서 예외가 발생합니다. 특정 조건에서 발생하는 예외 유형에 대한 자세한 내용은 이 페이지 하단에 링크된 deleteOne() 에 대한 API 문서를 참조하세요.

다음 스니펫은 sample_mflix 데이터베이스의 movies collection에서 단일 문서를 삭제합니다. 이 예제에서는 eq() 필터를 사용하여 title 이 텍스트 'The Garbage Pail Kids Movie' 와 정확히 일치하는 영화를 일치시킵니다.

참고

이 예제에서는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 알아보려면 연결 가이드를 참조하세요.

// Deletes a document from a collection by using the Java driver
package usage.examples;
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;
public class DeleteOne {
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 query = eq("title", "The Garbage Pail Kids Movie");
try {
// Deletes the first document that has a "title" value of "The Garbage Pail Kids Movie"
DeleteResult result = collection.deleteOne(query);
System.out.println("Deleted document count: " + result.getDeletedCount());
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to delete due to an error: " + me);
}
}
}
}

예제를 실행하면 deleteOne() 호출에서 전달한 쿼리 필터가 문서와 일치하여 문서를 제거하면 다음과 같은 출력이 표시됩니다.

Deleted document count: 1

쿼리 필터가 collection의 문서와 일치하지 않는 경우 deleteOne() 를 호출하면 문서가 제거되지 않고 다음이 반환됩니다.

Deleted document count: 0

Legacy API

레거시 API를 사용하는 경우 FAQ 페이지를 참조하여 코드 예제의 어떤 부분을 변경해야는지 확인하세요.

이 페이지에 언급된 클래스 및 메서드에 대한 추가 정보는 다음 API 설명서를 참조하세요.

  • DeleteOne()

  • DeleteResult

  • eq()

돌아가기

삭제 작업