티스토리 뷰

반응형


bulkWrite()를 이용해서 다수의 도큐먼트를 원하는 값으로 업데이트 할 수 있습니다.

아래 예제를 참고하여 코딩해 보세요..


List<WriteModel<Document>> updateDocuments = new ArrayList<WriteModel<Document>>();

for(업데이트할도큐먼트리스트) {

    Document filterDocument = new Document();

    filterDocument.append("_id", entityId); // 업데이트 대상을 찾을 조건

    //Update doc

    Document updateDocument = new Document();  // 업데이트할 필드와 값

    Document setDocument = new Document();

    setDocument.append("name", "xyz");

    setDocument.append("role", "abc");


    updateDocument.append("$set", setDocument);


    //Update option

    UpdateOptions updateOptions = new UpdateOptions();

    updateOptions.upsert(false); //if true, will create a new doc in case of unmatched find

    updateOptions.bypassDocumentValidation(false); //set true/false


    //Prepare list of Updates

    updateDocuments.add(

            new UpdateOneModel<Document>(

                    filterDocument,

                    updateDocument,

                    updateOptions));


} // end-for


//Bulk write options

BulkWriteOptions bulkWriteOptions = new BulkWriteOptions();

bulkWriteOptions.ordered(false); //False to allow parallel execution

bulkWriteOptions.bypassDocumentValidation(true);


MongoCollection<Document> mongoCollection = mongoDB.getCollection("myCollection");


BulkWriteResult bulkWriteResult = null;

try {

    //Perform bulk update

    bulkWriteResult = mongoCollection.bulkWrite(updateDocuments,

            bulkWriteOptions);

} catch (BulkWriteException e) {

    //Handle bulkwrite exception

    List<BulkWriteError> bulkWriteErrors = e.getWriteErrors();

    for (BulkWriteError bulkWriteError : bulkWriteErrors) {

        int failedIndex = bulkWriteError.getIndex();

        Long failedEntityId = entityIDs.get(failedIndex);

        System.out.println("Failed record: " + failedEntityId);

        //handle rollback

    }

}


int rowsUpdated = bulkWriteResult.getModifiedCount();


출처: http://ashutosh-srivastav-mongodb.blogspot.in/2017/09/mongodb-bulkwrite-java-api.html



반응형