기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.
Java를 사용하여 Amazon DocumentDB에서 CRUD 작업 수행
이 섹션에서는 MongoDB Java 드라이버를 사용하여 Amazon DocumentDB에서 CRUD(생성, 읽기, 업데이트, 삭제) 작업을 수행하는 방법을 설명합니다.
주제
DocumentDB 컬렉션에 문서 생성 및 삽입
Amazon DocumentDB에 문서를 삽입하면 컬렉션에 새 데이터를 추가할 수 있습니다. 요구 사항과 작업 중인 데이터의 양에 따라 삽입을 수행하는 방법에는 여러 가지가 있습니다. 컬렉션에 개별 문서를 삽입하는 가장 기본적인 방법은 입니다insertOne()
. 한 번에 여러 문서를 삽입하는 경우 단일 작업으로 문서 배열을 추가할 수 있는 insertMany()
메서드를 사용할 수 있습니다. DocumentDB 컬렉션에 많은 문서를 삽입하는 또 다른 방법은 입니다bulkWrite()
. 이 가이드에서는 DocumentDB 컬렉션에서 문서를 생성하는 이러한 모든 방법을 설명합니다.
insertOne()
먼저 Amazon DocumentDBB 컬렉션에 개별 문서를 삽입하는 방법을 살펴보겠습니다. 단일 문서 삽입은 insertOne()
메서드를 사용하여 수행됩니다. 이 메서드는 삽입을 위해 BsonDocumentInsertOneResult
Document article = new Document() .append("restaurantId", "REST-21G145") .append("name", "Future-proofed Intelligent Bronze Hat") .append("cuisine", "International") .append("rating", new Document() .append("average", 1.8) .append("totalReviews", 267)) .append("features", Arrays.asList("Outdoor Seating", "Live Music")); try { InsertOneResult result = collection.insertOne(article); System.out.println("Inserted document with the following id: " + result.getInsertedId()); } catch (MongoWriteException e) { // Handle duplicate key or other write errors System.err.println("Failed to insert document: " + e.getMessage()); throw e; } catch (MongoException e) { // Handle other MongoDB errors System.err.println("MongoDB error: " + e.getMessage()); throw e; }
를 사용할 때는 적절한 오류 처리를 포함해야 insertOne()
합니다. 예를 들어 위 코드에서 “restaurantId
”에는 고유한 인덱스가 있으므로이 코드를 다시 실행하면 MongoWriteException
다음과 같은가 발생합니다.
Failed to insert document: Write operation error on server docdbCluster.docdb.amazonaws.com:27017.
Write error: WriteError{code=11000, message='E11000 duplicate key error collection: Restaurants index: restaurantId_1', details={}}.
insertMany()
컬렉션에 많은 문서를 삽입하는 데 사용되는 기본 방법은 insertMany() 및 입니다bulkWrite()
.
메insertMany()
서드는 단일 작업으로 여러 문서를 삽입하는 가장 간단한 방법입니다. 문서 목록을 받아 컬렉션에 삽입합니다. 이 방법은 서로 독립적이며 특별한 처리 또는 혼합 작업이 필요하지 않은 새 문서 배치를 삽입할 때 적합합니다. 다음 코드는 파일에서 JSON 문서를 읽고 컬렉션에 삽입하는 방법을 보여줍니다. insertMany()
함수는 삽입된 모든 문서의 IDs를 가져오는 데 사용할 수 있는 InsertManyResult
InsertManyResult
객체를 반환합니다.
// Read JSON file content String content = new String(Files.readAllBytes(Paths.get(jsonFileName))); JSONArray jsonArray = new JSONArray(content); // Convert JSON articles to Documents List < Document > restaurants = new ArrayList < > (); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Document doc = Document.parse(jsonObject.toString()); restaurants.add(doc); } //insert documents in collection InsertManyResult result = collection.insertMany(restaurants); System.out.println("Count of inserted documents: " + result.getInsertedIds().size());
메bulkWrite()
서드를 사용하면가 단일 배치에서 여러 쓰기 작업(삽입, 업데이트, 삭제)을 수행할 수 있습니다. 다른 문서를 업데이트하는 동안 일부 문서를 삽입하는 등 단일 배치에서 다양한 유형의 작업을 수행해야 하는 bulkWrite()
경우를 사용할 수 있습니다.는 순서가 지정된 배치 쓰기와 순서가 지정되지 않은 배치 쓰기의 두 가지 유형을 bulkWrite()
지원합니다.
순서가 지정된 작업 - (기본값) Amazon DocumentDB는 쓰기 작업을 순차적으로 처리하고 오류가 처음 발생할 때 중지합니다. 이는 이후 작업이 이전 작업에 의존하는 경우와 같이 작업 순서가 중요한 경우에 유용합니다. 그러나 정렬된 작업은 일반적으로 정렬되지 않은 작업보다 느립니다. 순서가 지정된 작업의 경우 첫 번째 오류 시 배치가 중지되어 일부 작업이 처리되지 않을 수 있는 경우를 해결해야 합니다.
순서가 지정되지 않은 작업 - Amazon DocumentDB가 데이터베이스에서 삽입을 단일 실행으로 처리할 수 있습니다. 한 문서에 오류가 발생하면 작업은 나머지 문서로 계속됩니다. 이는 대량의 데이터를 삽입할 때 특히 유용하며 중복 키로 인해 일부 문서가 실패할 수 있는 데이터 마이그레이션 또는 대량 가져오기와 같은 일부 오류를 허용할 수 있습니다. 순서가 지정되지 않은 작업의 경우 일부 작업은 성공하지만 다른 작업은 실패하는 부분 성공 시나리오를 해결해야 합니다.
bulkWrite()
메서드를 사용할 때는 몇 가지 필수 클래스가 필요합니다. 먼저 클래스WriteModel
InsertOneModel
DeleteOneModel
UpdateManyModel
UpdateOneModel
DeleteManyModel
BulkWriteOptions
BulkWriteResult
오류 처리의 경우 MongoBulkWriteException
BulkWriteError
bulkWrite()
메서드 호출 실행 내에서 문서 목록을 삽입하고 단일 문서를 업데이트 및 삭제하는 예를 보여줍니다. 또한 코드는 BulkWriteOptions
bulkWrite()
작업의 BulkWriteResult
List < WriteModel < Document >> bulkOperations = new ArrayList < > (); // get list of 10 documents representing 10 restaurants List < Document > restaurantsToInsert = getSampleData(); for (Document doc: restaurantsToInsert) { bulkOperations.add(new InsertOneModel < > (doc)); } // Update operation bulkOperations.add(new UpdateOneModel < > ( new Document("restaurantId", "REST-Y2E9H5"), new Document("", new Document("stats.likes", 20)) .append("", new Document("rating.average", 4.5)))); // Delete operation bulkOperations.add(new DeleteOneModel < > (new Document("restaurantId", "REST-D2L431"))); // Perform bulkWrite operation try { BulkWriteOptions options = new BulkWriteOptions() .ordered(false); // Allow unordered inserts BulkWriteResult result = collection.bulkWrite(bulkOperations, options); System.out.println("Inserted: " + result.getInsertedCount()); System.out.println("Updated: " + result.getModifiedCount()); System.out.println("Deleted: " + result.getDeletedCount()); } catch (MongoBulkWriteException e) { System.err.println("Bulk write error occurred: " + e.getMessage()); // Log individual write errors for (BulkWriteError error: e.getWriteErrors()) { System.err.printf("Error at index %d: %s (Code: %d)%n", error.getIndex(), error.getMessage(), error.getCode()); // Log the problematic document Document errorDoc = new Document(error.getDetails()); if (errorDoc != null) { System.err.println("Problematic document: " + errorDoc); } } } catch (Exception e) { System.err.println("Error during bulkWrite: " + e.getMessage()); }
재시도 가능한 쓰기
MongoDB와 달리 Amazon DocumentDB는 재시도 가능한 쓰기를 지원하지 않습니다. 따라서 특히 네트워크 문제 또는 임시 서비스 가용성을 처리하기 위해 애플리케이션에서 사용자 지정 재시도 로직을 구현해야 합니다. 일반적으로 잘 구현된 재시도 전략에는 재시도 간의 지연을 늘리고 총 재시도 횟수를 제한하는 것이 포함됩니다. 오류 처리로 재시도 로직을 빌드하는 코드 샘플은 재시도 로직을 사용한 오류 처리 아래를 참조하세요.
DocumentDB 컬렉션에서 데이터 읽기 및 검색
Amazon DocumentDB에서 문서를 쿼리하는 것은 데이터를 정확하게 검색하고 조작할 수 있는 몇 가지 주요 구성 요소를 중심으로 합니다. find()
find()
메서드 외에도 Filters
FindIterable
Filters
클래스는 쿼리 필터를 구성하기 위한 유창한 API를 제공하는 MongoDB Java 드라이버의 유틸리티 클래스입니다. 이 클래스는 다양한 쿼리 조건을 나타내는 Bson
객체의 인스턴스를 생성하는 정적 팩토리 메서드를 제공합니다. 가장 일반적으로 사용되는 메서드에는 eq()
균등 비교, gt()
lt()
gte()
lte()
숫자 비교, 여러 조건 and()
or()
결합, in()
nin()
배열 멤버십 테스트, 패턴 일치 regex()
등이 있습니다. 클래스는 유형 안전하도록 설계되었으며 원시 문서 기반 쿼리에 비해 더 나은 컴파일 시간 확인을 제공하므로 Java 애플리케이션에서 DocumentDB 쿼리를 구성하는 데 선호되는 접근 방식입니다. 오류 처리는 견고하며 잘못된 필터 구성에 대해 명확한 예외가 발생합니다.
FindIterable
는 find()
메서드의 결과를 처리하도록 설계된 특수 인터페이스입니다. 쿼리 실행을 구체화하고 제어하는 다양한 방법을 제공하여 메서드 체인을 위한 유창한 API를 제공합니다. 인터페이스에는 반환된 문서 수 limit()
제한, skip()
페이지 매김, 결과 sort()
순서 지정, 특정 필드 projection()
선택, 인덱스 선택과 같은 필수 쿼리 수정 방법이 포함되어 hint()
있습니다. 의 배치, 건너뛰기 및 제한 작업은 데이터베이스에서 문서를 검색하고 처리하는 방법을 제어하는 데 도움이 되는 FindIterable
필수 페이지 매김 및 데이터 관리 도구입니다.
일괄 처리(batchSize
)는 DocumentDB가 단일 네트워크 왕복으로 클라이언트에 반환하는 문서 수를 제어합니다. 배치 크기를 설정하면 DocumentDB는 일치하는 모든 문서를 한 번에 반환하지 않고 대신 지정된 배치 크기의 그룹으로 반환합니다.
건너뛰기를 사용하면 결과의 시작점을 오프셋하여 일치 항목을 반환하기 전에 지정된 수의 문서를 건너뛰도록 DocumentDB에 지시할 수 있습니다. 예를 들어 skip(20)
는 처음 20개의 일치하는 문서를 우회합니다. 이는 결과의 후속 페이지를 검색하려는 페이지 매김 시나리오에서 일반적으로 사용됩니다.
제한은 쿼리에서 반환할 수 있는 총 문서 수를 제한합니다. 를 지정하면 데이터베이스에 일치하는 항목이 더 있더라도 limit(n)
DocumentDB는 'n' 문서를 반환한 후 문서 반환을 중지합니다.
FindIterable
는 Amazon DocumentDB에서 문서를 검색할 때 반복자와 커서 패턴을 모두 지원합니다. 를 FindIterable
반복자로 사용하면 문서를 느리게 로드할 수 있으며 애플리케이션에서 요청할 때만 문서를 가져올 수 있다는 이점이 있습니다. 반복기 사용의 또 다른 이점은 클러스터에 대한 연결을 유지할 책임이 없으므로 연결을 명시적으로 닫을 필요가 없다는 것입니다.
FindIterable
는 Amazon DocumentDB 쿼리로 작업할 때 커서 패턴을 사용할 수 MongoCursor
MongoCursor
는 데이터베이스 작업 및 리소스 관리를 제어하는 MongoDB Java 드라이버별 구현입니다. AutoCloseable
인터페이스를 구현하여 try-with-resources 통해 명시적 리소스 관리를 가능하게 합니다.이 블록은 데이터베이스 연결을 올바르게 닫고 서버 리소스를 확보하는 데 매우 중요합니다. 기본적으로 커서는 10분 후에 시간 초과되며 DocumentDB는이 시간 초과 동작을 변경할 수 있는 옵션을 제공하지 않습니다. 배치 데이터로 작업할 때는 커서 시간이 초과되기 전에 다음 데이터 배치를 검색해야 합니다. 를 사용할 때 한 가지 주요 고려 MongoCursor
사항은 리소스 누수를 방지하기 위해 명시적으로 닫아야 한다는 것입니다.
이 단원에서는 , find()
Filters
및에 대한 몇 가지 예제가 나와 있습니다FindIterable
.
다음 코드 예제에서는를 사용하여 “restaurantId” 필드를 사용하여 단일 문서를 find()
검색하는 방법을 보여줍니다.
Document filter = new Document("restaurantId", "REST-21G145"); Document result = collection.find(filter).first();
를 사용하면 컴파일 시간 오류 검사를 개선할 Filters
수 있지만 java 드라이버를 사용하면 find()
메서드에서 직접 Bson
필터를 지정할 수도 있습니다. 다음 예제 코드는 Bson
문서를에 전달합니다find()
.
result = collection.find(new Document("$and", Arrays.asList( new Document("rating.totalReviews", new Document("$gt", 1000)), new Document("priceRange", "$$"))))
다음 예제 코드는에서 Filters
클래스를 사용하는 몇 가지 예를 보여줍니다. find()
FindIterable < Document > results; // Exact match results = collection.find(Filters.eq("name", "Thai Curry Palace")); // Not equal results = collection.find(Filters.ne("cuisine", "Thai")); // find an element in an array results = collection.find(Filters.in("features", Arrays.asList("Private Dining"))); // Greater than results = collection.find(Filters.gt("rating.average", 3.5)); // Between (inclusive) results = collection.find(Filters.and( Filters.gte("rating.totalReviews", 100), Filters.lte("rating.totalReviews", 200))); // AND results = collection.find(Filters.and( Filters.eq("cuisine", "Thai"), Filters.gt("rating.average", 4.5))); // OR results = collection.find(Filters.or( Filters.eq("cuisine", "Thai"), Filters.eq("cuisine", "American"))); // All document where the Field exists results = collection.find(Filters.exists("michelin")); // Regex results = collection.find(Filters.regex("name", Pattern.compile("Curry", Pattern.CASE_INSENSITIVE))); // Find all document where the array contain the list of value regardless of its order results = collection.find(Filters.all("features", Arrays.asList("Private Dining", "Parking"))); // Array size results = collection.find(Filters.size("features", 4));
다음 예제에서는 batchSize()
FindIterable
객체에서 sort()
, skip()
limit()
, 및 작업을 연결하는 방법을 보여줍니다. 이러한 작업이 제공되는 순서는 쿼리 성능에 영향을 미칩니다. 가장 좋은 방법은 이러한 작업의 순서가 , sort()
, projection()
skip()
limit()
및 이어야 한다는 것입니다batchSize()
.
FindIterable < Document > results = collection.find(Filters.gt("rating.totalReviews", 1000)) // Sorting .sort(Sorts.orderBy( Sorts.descending("address.city"), Sorts.ascending("cuisine"))) // Field selection .projection(Projections.fields( Projections.include("name", "cuisine", "priceRange"), Projections.excludeId())) // Pagination .skip(20) .limit(10) .batchSize(2);
다음 예제 코드는에서 반복자를 생성하는 방법을 보여줍니다FindIterable
. Java의 forEach
구문을 사용하여 결과 집합을 통과합니다.
collection.find(Filters.eq("cuisine", "American")).forEach(doc -> System.out.println(doc.toJson()));
마지막 find()
코드 예제에서는 문서 검색에 cursor()
를 사용하는 방법을 보여줍니다. 코드가 시도 블록을 종료할 때 커서가 닫히도록 시도 블록에 커서를 생성합니다.
try (MongoCursor < Document > cursor = collection.find(Filters.eq("cuisine", "American")) .batchSize(25) .cursor()) { while (cursor.hasNext()) { Document doc = cursor.next(); System.out.println(doc.toJson()); } } // Cursor automatically closed
DocumentDB 컬렉션의 기존 문서 업데이트
Amazon DocumentDB는 기존 문서를 수정하고 존재하지 않을 때 새 문서를 삽입할 수 있는 유연하고 강력한 메커니즘을 제공합니다. MongoDB Java 드라이버는 updateOne()
단일 문서 업데이트, updateMany()
여러 문서 업데이트, replaceOne()
전체 문서 교체 등 여러 가지 업데이트 방법을 제공합니다. 이 세 가지 방법 외에도 Updates
UpdateOptions
UpdateResult
MongoDB Java 드라이버의 Updates
클래스는 업데이트 연산자를 생성하기 위한 정적 팩토리 메서드를 제공하는 유틸리티 클래스입니다. 유형 안전 및 읽기 가능한 방식으로 업데이트 작업을 구성하기 위한 기본 빌더 역할을 합니다. set()
, unset()
및와 같은 기본 메서드를 inc()
사용하면 문서를 직접 수정할 수 있습니다. 여러 업데이트 작업을 원자적으로 실행하여 데이터 일관성을 보장할 수 있는 Updates.combine()
메서드를 사용하여 여러 작업을 결합하면이 클래스의 성능이 분명해집니다.
UpdateOptions
는 문서 업데이트 작업에 필수적인 사용자 지정 기능을 제공하는 MongoDB의 Java 드라이버에 있는 강력한 구성 클래스입니다. 이 클래스의 두 가지 중요한 측면은 업데이트 작업에 대한 업서트 및 배열 필터 지원을 제공하는 것입니다. 를 통해 활성화된 업서트 기능을 upsert(true)
사용하면 업데이트 작업 중에 일치하는 문서를 찾을 수 없는 경우 새 문서를 생성할 수 있습니다. arrayFilters()
를 통해 업데이트 작업은 특정 기준을 충족하는 배열 요소를 정확하게 업데이트할 수 있습니다.
UpdateResult
MongoDB의 Java 드라이버에서는 업데이트 작업의 결과를 자세히 설명하는 피드백 메커니즘을 제공합니다. 이 클래스는 업데이트 기준과 일치하는 문서 수(matchedCount
), 실제로 수정된 문서 수(modifiedCount
), 업서트된 문서에 대한 정보()의 세 가지 주요 지표를 캡슐화합니다upsertedId
. 이러한 지표를 이해하는 것은 적절한 오류 처리, 업데이트 작업 확인 및 애플리케이션의 데이터 일관성 유지에 필수적입니다.
단일 문서 업데이트 및 교체
DocumentDB에서는 updateOne() 메서드를 사용하여 단일 문서를 업데이트할 수 있습니다. 이 메서드는 업데이트할 문서를 식별하기 위해 일반적으로 Filters
클래스에서 제공하는 필터 파라미터, 업데이트할 필드를 결정하는 Updat
e 파라미터, 업데이트에 대한 다양한 옵션을 설정하는 선택적 UpdateOptions
파라미터를 사용합니다. updateOne()
메서드를 사용하면 선택 기준과 일치하는 첫 번째 문서만 업데이트됩니다. 다음 예제 코드는 문서 하나의 단일 필드를 업데이트합니다.
collection.updateOne(Filters.eq("restaurantId", "REST-Y2E9H5"), Updates.set("name", "Amazing Japanese sushi"));
한 문서에서 여러 필드를 업데이트하려면 다음 예제Update.combine()
와 같이와 updateOne()
함께를 사용합니다. 이 예제에서는 문서의 배열에 항목을 추가하는 방법도 보여줍니다.
List<Bson> updates = new ArrayList<>(); // Basic field updates updates.add(Updates.set("name", "Shanghai Best")); // Array operations updates.add(Updates.addEachToSet("features", Arrays.asList("Live Music"))); // Counter updates updates.add(Updates.inc("rating.totalReviews", 10)); // Combine all updates Bson combinedUpdates = Updates.combine(updates); // Execute automic update with one call collection.updateOne(Filters.eq("restaurantId","REST-1J83NH"), combinedUpdates);
다음 코드 예제에서는 데이터베이스에서 문서를 업데이트하는 방법을 보여줍니다. 지정된 문서가 없는 경우 작업은 자동으로 새 문서로 삽입합니다. 이 코드는 UpdateResult
객체를 통해 사용 가능한 지표를 사용하는 방법도 보여줍니다.
Bson filter = Filters.eq("restaurantId", "REST-0Y9GL0"); Bson update = Updates.set("cuisine", "Indian"); // Upsert operation UpdateOptions options = new UpdateOptions().upsert(true); UpdateResult result = collection.updateOne(filter, update, options); if (result.getUpsertedId() != null) { System.out.println("Inserted document with _id: " + result.getUpsertedId()); } else { System.out.println("Updated " + result.getModifiedCount() + " document(s)"); }
다음 코드 예제에서는 개별 필드를 업데이트하는 대신 replaceOne()
메서드를 사용하여 기존 문서를 새 문서로 완전히 바꾸는 방법을 보여줍니다. replaceOne()
메서드는 원본의 _id
필드만 보존하여 전체 문서를 덮어씁니다. 여러 문서가 필터 기준과 일치하는 경우 처음 발견된 문서만 대체됩니다.
Document newDocument = new Document() .append("restaurantId", "REST-0Y9GL0") .append("name", "Bhiryani Adda") .append("cuisine", "Indian") .append("rating", new Document() .append("average", 4.8) .append("totalReviews", 267)) .append("features", Arrays.asList("Outdoor Seating", "Live Music")); UpdateResult result = collection.replaceOne( Filters.eq("restaurantId", "REST-0Y9GL0"), newDocument); System.out.printf("Modified %d document%n", result.getModifiedCount());
여러 문서 업데이트
컬렉션에서 여러 문서를 동시에 업데이트하는 두 가지 방법이 있습니다. updateMany()
메서드를 사용하거나 bulkWrite()
메서드와 UpdateManyModel
updateMany()
메서드는 필터 파라미터를 사용하여 업데이트할 문서를 선택하고, Update
파라미터를 사용하여 업데이트할 필드를 식별하고, 선택적 UpdateOptions
파라미터를 사용하여 업데이트 옵션을 지정합니다.
다음 예제 코드는 updateMany()
메서드의 사용을 보여줍니다.
Bson filter = Filters.and( Filters.in("features", Arrays.asList("Private Dining")), Filters.eq("cuisine", "Thai")); UpdateResult result1 = collection.updateMany(filter, Updates.set("priceRange", "$$$"));
다음 예제 코드는 동일한 업데이트를 사용하는 bulkWrite()
메서드를 보여줍니다.
BulkWriteOptions options = new BulkWriteOptions().ordered(false); List < WriteModel < Document >> updates = new ArrayList < > (); Bson filter = Filters.and( Filters.in("features", Arrays.asList("Private Dining")), Filters.eq("cuisine", "Indian")); Bson updateField = Updates.set("priceRange", "$$$"); updates.add(new UpdateManyModel < > (filter, updateField)); BulkWriteResult result = collection.bulkWrite(updates, options); System.out.printf("Modified %d document%n", result.getModifiedCount());
DocumentDB 컬렉션에서 문서 제거
MongoDB Java 드라이버는 단일 문서를 deleteOne()
제거하고 특정 기준과 일치하는 여러 문서를 제거하기 deleteMany()
위해를 제공합니다. 업데이트와 마찬가지로 삭제 작업을 bulkWrite()
메서드와 함께 사용할 수도 있습니다. deleteOne()
및 모두 삭제된 문서 수를 포함하여 작업 결과에 대한 정보를 제공하는 DeleteResult
deleteMany()
반환합니다. 다음은를 사용하여 여러 문서를 deleteMany()
제거하는 예입니다.
Bson filter = Filters.and( Filters.eq("cuisine", "Thai"), Filters.lt("rating.totalReviews", 50)); DeleteResult result = collection.deleteMany(filter); System.out.printf("Deleted %d document%n", result.getDeletedCount());
재시도 로직을 사용한 오류 처리
Amazon DocumentDB에 대한 강력한 오류 처리 전략은 오류 분류를 재시도 가능(예: 네트워크 제한 시간, 연결 문제) 및 재시도 불가능(예: 인증 실패, 잘못된 쿼리)으로 구현해야 합니다. 재시도해야 하는 오류로 인한 작업 실패의 경우 각 재시도와 최대 재시도 사이에 시간 지연을 구현해야 합니다. CRUD 작업은 MongoException
int MAX_RETRIES = 3; int INITIAL_DELAY_MS = 1000; int retryCount = 0; while (true) { try { crud_operation(); //perform crud that will throw MongoException or one of its subclass break; } catch (MongoException e) { if (retryCount < MAX_RETRIES) { retryCount++; long delayMs = INITIAL_DELAY_MS * (long) Math.pow(2, retryCount - 1); try { TimeUnit.MILLISECONDS.sleep(delayMs); } catch (InterruptedException t) { Thread.currentThread().interrupt(); throw new RuntimeException("Retry interrupted", t); } continue; } else throw new RuntimeException("Crud operation failed", e); } }