Docs Menu
Docs Home
/ / /
Kotlin Sync 드라이버
/

대량 쓰기 작업

이 가이드 에서는 대량 쓰기 (write) 작업 을 사용하여 단일 데이터베이스 호출에서 여러 쓰기 (write) 작업을 수행하는 방법에 학습 설명합니다.

문서 삽입하고, 다른 여러 문서를 업데이트 다음, 문서 삭제 하려는 시나리오를 가정해 보겠습니다. 개별 메서드를 사용하는 경우 각 작업에는 자체 데이터베이스 호출이 필요합니다.

대량 쓰기 (write) 작업을 사용하면 더 적은 수의 데이터베이스 호출로 여러 쓰기 (write) 작업을 수행할 수 있습니다. 다음 수준에서 대량 쓰기 (write) 작업을 수행할 수 있습니다.

  • 컬렉션: 메서드를 사용하여 MongoCollection.bulkWrite() 단일 컬렉션 에 대해 대량 쓰기 (write) 작업을 수행할 수 있습니다. 이 메서드에서는 각 종류의 쓰기 (write) 작업에 하나 이상의 데이터베이스 호출이 필요합니다. 예시 를 들어 MongoCollection.bulkWrite() 는 여러 업데이트 작업을 한 번의 호출에 처리하지만 삽입 작업과 바꾸기 작업에 대해 데이터베이스 두 번 개별적으로 호출합니다.

  • 클라이언트: 애플리케이션 MongoDB Server 버전 이상에 연결되는 8.0 경우 메서드를 사용하여 MongoClient.bulkWrite() 동일한 클러스터 의 여러 컬렉션 및 데이터베이스에서 대량 쓰기 (write) 작업을 수행할 수 있습니다. 이 메서드는 한 번의 데이터베이스 호출로 모든 쓰기 (write) 작업을 수행합니다.

이 가이드 의 예제에서는 Atlas 샘플 데이터 세트의 및 컬렉션을 사용합니다.sample_restaurants.restaurants sample_mflix.movies 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 Atlas 시작하기 가이드 참조하세요.

이러한 컬렉션의 문서는 다음 코틀린 (Kotlin) 데이터 클래스에 의해 모델링됩니다.

data class Restaurant(
val name: String,
val borough: String,
val cuisine: String,
val stars: Int? = null,
)
data class Movie(
val title: String,
val year: Int,
val seen: Boolean? = null,
)

대량 쓰기 (write) 작업에는 하나 이상의 쓰기 (write) 작업이 포함됩니다. 컬렉션 수준에서 대량 쓰기 (write) 작업을 수행하려면 WriteModel 문서의 ListMongoCollection.bulkWrite() 메서드에 전달합니다. WriteModel 는 쓰기 (write) 작업을 나타내는 모델입니다.

수행하려는 각 쓰기 (write) 작업에 대해 WriteModel에서 상속되는 다음 클래스 중 하나의 인스턴스 만듭니다.

  • InsertOneModel

  • UpdateOneModel

  • UpdateManyModel

  • ReplaceOneModel

  • DeleteOneModel

  • DeleteManyModel

다음 섹션에서는 이전 클래스의 인스턴스를 만들고 사용하는 방법을 보여줍니다. 대량 작업 수행 섹션에서는 모델 목록을 bulkWrite() 메서드에 전달하여 대량 작업을 수행하는 방법을 보여 줍니다.

삽입 작업을 수행하려면 InsertOneModel 인스턴스 를 만들고 삽입하려는 문서 를 지정합니다.

다음 예에서는 InsertOneModel 인스턴스를 만듭니다.

val blueMoon = InsertOneModel(Restaurant("Blue Moon Grill", "Brooklyn", "American"))

여러 문서를 삽입하려면 각 문서 에 대해 InsertOneModel 인스턴스 를 만듭니다.

중요

대량 작업을 수행할 때 InsertOneModel 는 컬렉션 에 이미 존재하는 _id 값이 있는 문서 의 삽입을 지시할 수 없습니다. 이 상황에서 운전자 MongoBulkWriteException를 발생시킵니다.

문서 를 업데이트 하려면 UpdateOneModel 인스턴스 를 만들고 다음 인수를 전달합니다.

  • 컬렉션의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터

  • 수행하려는 업데이트 작업입니다. 업데이트 연산자에 대한 자세한 내용은 MongoDB Server 매뉴얼의 필드 업데이트 연산자 가이드 참조하세요.

UpdateOneModel 인스턴스 는 쿼리 필터하다 와 일치 하는 첫 번째 문서 에 대한 업데이트 를 지정합니다.

다음 예에서는 UpdateOneModel 인스턴스를 만듭니다.

val updateOneFilter = Filters.eq(Restaurant::name.name, "White Horse Tavern")
val updateOneDoc = Updates.set(Restaurant::borough.name, "Queens")
val tavernUpdate = UpdateOneModel<Restaurant>(updateOneFilter, updateOneDoc)

여러 문서가 UpdateOneModel 인스턴스 에 지정된 쿼리 필터하다 와 일치하는 경우 작업은 첫 번째 결과를 업데이트합니다. 다음 코드와 같이 UpdateOptions 인스턴스 에서 정렬을 지정하여 서버 업데이트 작업을 수행하기 전에 일치하는 문서에 순서를 적용 할 수 있습니다.

val opts = UpdateOptions().sort(Sorts.ascending(Restaurant::name.name))

여러 문서를 업데이트 하려면 UpdateManyModel UpdateOneModel인스턴스 를 만들고 와 동일한 인수를 전달합니다. UpdateManyModel 클래스는 쿼리 필터하다 와 일치하는 모든 문서에 대한 업데이트를 지정합니다.

다음 예시 UpdateManyModel 의 인스턴스 만들어 운전자 일치하는 모든 문서를 업데이트 하도록 지시합니다.

val updateManyFilter = Filters.eq(Restaurant::name.name, "Wendy's")
val updateManyDoc = Updates.set(Restaurant::cuisine.name, "Fast food")
val wendysUpdate = UpdateManyModel<Restaurant>(updateManyFilter, updateManyDoc)

바꾸기 작업은 지정된 문서 의 모든 필드와 값을 제거하고 사용자가 지정한 새 필드와 값으로 바꿉니다. 대체 작업을 수행하려면 ReplaceOneModel 인스턴스 를 만들고 쿼리 필터하다 와 일치하는 문서 를 대체할 필드 및 값을 전달합니다.

다음 예에서는 ReplaceOneModel 인스턴스를 만듭니다.

val replaceFilter = Filters.eq(Restaurant::name.name, "Cooper Town Diner")
val replaceDoc = Restaurant("Smith Town Diner", "Brooklyn", "American")
val replacement = ReplaceOneModel(replaceFilter, replaceDoc)

여러 문서가 ReplaceOneModel 인스턴스 에 지정된 쿼리 필터하다 와 일치하는 경우 작업은 첫 번째 결과를 대체합니다. 다음 코드와 같이 ReplaceOptions 인스턴스 에서 정렬을 지정하여 서버 바꾸기 작업을 수행하기 전에 일치하는 문서에 순서를 적용 할 수 있습니다.

val opts = ReplaceOptions().sort(Sorts.ascending(Restaurant::name.name))

여러 문서 바꾸기

여러 문서를 바꾸려면 각 문서 에 대해 ReplaceOneModel 인스턴스 를 만듭니다.

문서 를 삭제 하려면 DeleteOneModel 인스턴스 를 만들고 삭제 하려는 문서 를 지정하는 쿼리 필터하다 를 전달합니다. DeleteOneModel 인스턴스 는 쿼리 필터하다 와 일치 하는 첫 번째 문서 만 삭제 하는 지침을 제공합니다.

다음 예에서는 DeleteOneModel 인스턴스를 만듭니다.

val deleteOne = DeleteOneModel<Restaurant>(Filters.eq(
Restaurant::name.name,
"Morris Park Bake Shop"
))

여러 문서를 삭제 하려면 DeleteManyModel 인스턴스 를 만들고 삭제 하려는 문서 를 지정하는 쿼리 필터하다 를 전달합니다. DeleteManyModel 인스턴스 는 쿼리 필터하다 와 일치하는 모든 문서를 제거 하는 지침을 제공합니다.

다음 예에서는 DeleteManyModel 인스턴스를 만듭니다.

val deleteMany = DeleteManyModel<Restaurant>(Filters.eq(
Restaurant::cuisine.name,
"Experimental"
))

수행하려는 각 작업에 대한 모델 인스턴스 를 정의한 후 이러한 인스턴스 목록을 bulkWrite() 메서드에 전달합니다. 기본값 으로 이 메서드는 모델 목록에 지정된 순서대로 작업을 실행합니다.

다음 예시 에서는 bulkWrite() 메서드를 사용하여 여러 쓰기 (write) 작업을 수행합니다.

val insertOneMdl = InsertOneModel(Restaurant("Red's Pizza", "Brooklyn", "Pizzeria"))
val updateOneMdl = UpdateOneModel<Restaurant>(
Filters.eq(Restaurant::name.name, "Moonlit Tavern"),
Updates.set(Restaurant::borough.name, "Queens")
)
val deleteManyMdl = DeleteManyModel<Restaurant>(
Filters.eq(Restaurant::name.name, "Crepe")
)
val bulkResult = collection.bulkWrite(
listOf(insertOneMdl, updateOneMdl, deleteManyMdl)
)
println(bulkResult)
AcknowledgedBulkWriteResult{insertedCount=1, matchedCount=5, removedCount=3,
modifiedCount=2, upserts=[], inserts=[BulkWriteInsert{index=0,
id=BsonObjectId{value=...}}]}

쓰기 (write) 작업 중 하나라도 실패하면 코틀린 동기 (Kotlin Sync) 운전자 BulkWriteError 를 발생시키고 추가 작업을 수행하지 않습니다. BulkWriteError 은(는) 실패한 작업과 예외에 대한 세부 정보가 포함된 details 필드 제공합니다.

참고

운전자 가 대량 작업을 실행할 때 대상 컬렉션 의 쓰기 고려 (write concern) 를 사용합니다. 운전자 는 실행 순서에 관계없이 모든 작업을 시도한 후 모든 쓰기 고려 (write concern) 오류를 보고합니다.

bulkWrite() 메서드는 대량 쓰기 (write) 작업을 구성하는 데 사용할 수 있는 옵션을 지정하는 매개 변수를 선택적으로 허용합니다. 옵션을 지정하지 않으면 운전자 는 기본값 설정으로 대량 작업을 수행합니다.

다음 표에서는 BulkWriteOptions 인스턴스 를 구성하는 데 사용할 수 있는 setter 메서드에 대해 설명합니다.

속성
설명

ordered()

If true, the driver performs the write operations in the order provided. If an error occurs, the remaining operations are not attempted.

If false, the driver performs the operations in an arbitrary order and attempts to perform all operations.
Defaults to true.

bypassDocumentValidation()

Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.
Defaults to false.

comment()

Sets a comment to attach to the operation.

let()

Provides a map of parameter names and values to set top-level variables for the operation. Values must be constant or closed expressions that don't reference document fields.

다음 코드는 옵션을 생성하고 ordered(false) 옵션을 사용하여 순서가 지정되지 않은 대량 쓰기 (write) 를 지정합니다. 그런 다음 이 예시 에서는 bulkWrite() 메서드를 사용하여 대량 작업을 수행합니다.

val opts = BulkWriteOptions().ordered(false)
collection.bulkWrite(bulkOperations, opts)

순서가 지정되지 않은 대량 쓰기 (write) 의 쓰기 (write) 작업 중 하나라도 실패하면 코틀린 동기 (Kotlin Sync) 운전자 는 모든 작업을 시도한 후에만 오류를 보고합니다.

참고

순서가 지정되지 않은 대량 작업은 실행 순서를 보장하지 않습니다. 순서는 런타임을 최적화하기 위해 나열하는 방식과 다를 수 있습니다.

bulkWrite() 메서드는 BulkWriteResult 객체 를 반환합니다. BulkWriteResult 인스턴스 에서 다음 정보에 액세스 할 수 있습니다.

속성
설명

wasAcknowledged()

Indicates if the server acknowledged the write operation.

getDeletedCount()

The number of documents deleted, if any.

getInsertedCount()

The number of documents inserted, if any.

getInserts()

The list of inserted documents, if any.

getMatchedCount()

The number of documents matched for an update, if applicable.

getModifiedCount()

The number of documents modified, if any.

getUpserts()

The list of upserted documents, if any.

MongoDB Server 8.0 이상을 실행 배포서버 에 연결할 때 MongoClient.bulkWrite() 메서드를 사용하여 동일한 클러스터 의 여러 데이터베이스 및 컬렉션에 쓰기 (write) 수 있습니다. MongoClient.bulkWrite() 메서드는 한 번의 호출로 모든 쓰기 (write) 작업을 수행합니다.

MongoClient.bulkWrite() 메서드는 ClientNamespacedWriteModel 인스턴스 목록을 사용하여 다양한 쓰기 (write) 작업을 나타냅니다. 인스턴스 메서드를 사용하여 ClientNamespacedWriteModel 인터페이스의 인스턴스를 구성할 수 있습니다. 예시 를 들어 ClientNamespacedInsertOneModel 의 인스턴스 하나의 문서 삽입하는 작업을 나타내며 ClientNamespacedWriteModel.insertOne() 메서드를 사용하여 이 모델을 만들 수 있습니다.

모델과 해당 인스턴스 메서드는 아래 표에 설명되어 있습니다.

모델
인스턴스 메서드
설명
매개변수

ClientNamespacedInsertOneModel

insertOne()

namespace에 문서 삽입할 모델을 만듭니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

document: 삽입할 문서

ClientNamespacedUpdateOneModel

updateOne()

filter와 일치하는 namespace 의 첫 번째 문서 업데이트 모델을 만듭니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 업데이트 할 문서 선택하는 필터

update: 일치하는 문서 에 적용 업데이트

updatePipeline: 일치하는 문서 에 적용 파이프라인 업데이트

options: (선택 사항) 문서 업데이트 시 적용 옵션

update 또는 updatePipeline 매개변수 값을 전달해야 합니다.

ClientNamespacedUpdateManyModel

updateMany()

filter와 일치하는 namespace 의 모든 문서를 업데이트 모델을 만듭니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 업데이트 할 문서를 선택하는 필터

update: 일치하는 문서에 적용 업데이트

updatePipeline: 일치하는 문서에 적용 파이프라인 업데이트

options: (선택 사항) 문서 업데이트 시 적용 옵션

update 또는 updatePipeline 매개변수 값을 전달해야 합니다.

ClientNamespacedReplaceOneModel

replaceOne()

filter와 일치하는 namespace 의 첫 번째 문서 대체할 모델을 만듭니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 대체할 문서 선택하는 필터

replacement: 대체 문서

options: (선택 사항) 문서를 교체할 때 적용 옵션

ClientNamespacedDeleteOneModel

deleteOne()

filter와 일치하는 namespace 의 첫 번째 문서 삭제 하는 모델을 생성합니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 삭제 문서 선택하는 필터

option: (선택 사항) 문서 삭제할 때 적용 할 옵션

ClientNamespacedDeleteManyModel

deleteMany()

filter와(과) 일치하는 namespace 의 모든 문서를 삭제 하는 모델을 생성합니다.

namespace: 쓰기 (write) 데이터베이스 및 컬렉션

filter: 삭제 문서를 선택하는 필터

option: (선택 사항) 문서를 삭제할 때 적용 할 옵션

다음 섹션에서는 모델을 만들고 클라이언트 bulkWrite() 메서드를 사용하는 방법에 대한 몇 가지 예를 제공합니다.

이 예시 두 개의 문서를 삽입하기 위한 지침이 포함된 모델을 만드는 방법을 보여 줍니다. 한 문서 sample_restaurants.restaurants 컬렉션 에 삽입되고 다른 문서 sample_mflix.movies 컬렉션 에 삽입됩니다. MongoNamespace 인스턴스 각 쓰기 (write) 작업이 적용되는 대상 데이터베이스 및 컬렉션 정의합니다.

val restaurantToInsert = ClientNamespacedWriteModel
.insertOne(
MongoNamespace("sample_restaurants", "restaurants"),
Restaurant("Blue Moon Grill", "Brooklyn", "American")
)
val movieToInsert = ClientNamespacedWriteModel
.insertOne(
MongoNamespace("sample_mflix", "movies"),
Movie("Silly Days", 2022)
)

다음 예시 bulkWrite() 메서드를 사용하여 sample_restaurants.restaurantssample_mflix.movies 컬렉션의 기존 문서를 업데이트 방법을 보여 줍니다.

val restaurantUpdate = ClientNamespacedWriteModel
.updateOne(
MongoNamespace("sample_restaurants", "restaurants"),
Filters.eq(Restaurant::name.name, "Villa Berulia"),
Updates.inc(Restaurant::stars.name, 1)
)
val movieUpdate = ClientNamespacedWriteModel
.updateMany(
MongoNamespace("sample_mflix", "movies"),
Filters.eq(Movie::title.name, "Carrie"),
Updates.set(Movie::seen.name, true)
)

이 예시 restaurants 컬렉션 에서 name 값이 "Villa Berulia" 인 문서 에서 stars 필드 의 값을 1 만큼 증가시킵니다. 또한 movies 컬렉션 에서 title 값이 "Carrie" 인 모든 문서에서 seen 필드 값을 true 로 설정합니다.

여러 문서가 ClientNamespacedUpdateOneModel 인스턴스 에 지정된 쿼리 필터하다 와 일치하는 경우 작업은 첫 번째 결과를 업데이트합니다. 다음 코드와 같이 서버 업데이트 작업을 수행하기 전에 ClientUpdateOneOptions 인스턴스에서 정렬 순서를 지정하여 일치하는 문서에 순서를 적용할 수 있습니다.

val options = ClientUpdateOneOptions
.clientUpdateOneOptions()
.sort(Sorts.ascending("_id"))

다음 예시 sample_restaurants.restaurantssample_mflix.movies 컬렉션의 기존 문서를 대체하는 모델을 만드는 방법을 보여 줍니다.

val restaurantReplacement = ClientNamespacedWriteModel
.replaceOne(
MongoNamespace("sample_restaurants", "restaurants"),
Filters.eq("_id", 1),
Restaurant("Smith Town Diner", "Brooklyn", "American")
)
val movieReplacement = ClientNamespacedWriteModel
.replaceOne(
MongoNamespace("sample_mflix", "movies"),
Filters.eq("_id", 1),
Movie("Loving Sylvie", 1999)
)

이 예시 성공적으로 실행되면 restaurants 컬렉션 에서 _id 값이 1 인 문서 새 문서 로 대체됩니다. movies 컬렉션 의 _id 값이 1 인 문서 도 새 문서 로 대체됩니다.

여러 문서가 ClientNamespacedReplaceOneModel 인스턴스 에 지정된 쿼리 필터하다 와 일치하는 경우 작업은 첫 번째 결과를 대체합니다. 다음 코드에 표시된 것처럼 운전자 바꾸기 작업을 수행하기 전에 ClientReplaceOneOptions 인스턴스 에서 정렬 순서를 지정하여 일치하는 문서에 순서를 적용 할 수 있습니다.

val options = ClientReplaceOneOptions
.clientReplaceOneOptions()
.sort(Sorts.ascending("_id"))

수행하려는 각 작업에 대해 ClientNamespacedWriteModel 인스턴스 정의한 후 이러한 인스턴스 목록을 클라이언트 bulkWrite() 메서드에 전달합니다. 기본값 으로 이 메서드는 지정된 순서대로 작업을 실행합니다.

다음 예시 에서는 bulkWrite() 메서드를 사용하여 여러 쓰기 (write) 작업을 수행합니다.

val restaurantNamespace = MongoNamespace("sample_restaurants", "restaurants")
val movieNamespace = MongoNamespace("sample_mflix", "movies")
val bulkOperations = listOf(
ClientNamespacedWriteModel
.insertOne(
restaurantNamespace,
Restaurant("Drea's", "Brooklyn", "Mexican")
),
ClientNamespacedWriteModel
.replaceOne(
movieNamespace,
Filters.eq("_id", 1),
Movie("Underneath It All", 2002)
)
)
val clientBulkResult = mongoClient
.bulkWrite(bulkOperations)
println(clientBulkResult.toString())
AcknowledgedSummaryClientBulkWriteResult{insertedCount=1, matchedCount=1, ...}

쓰기 (write) 작업 중 하나라도 실패하면 운전자 ClientBulkWriteException 를 발생시키고 더 이상 개별 작업을 수행하지 않습니다. ClientBulkWriteException 에는 개별 장애에 대한 세부 정보를 제공하는 ClientBulkWriteException.getWriteErrors() 메서드를 사용하여 액세스할 수 있는 BulkWriteError 가 포함되어 있습니다.

ClientBulkWriteOptions 인스턴스 bulkWrite() 메서드에 전달하여 운전자 대량 쓰기 (write) 작업을 수행하는 방식을 사용자 지정할 수 있습니다.

기본값 으로 운전자 오류가 발생하거나 작업이 성공적으로 완료될 때까지 지정한 순서대로 개별 작업을 대량 작업으로 실행합니다.

그러나 ClientBulkWriteOptions 인스턴스 만들 때 falseordered() 메서드에 전달하여 운전자 순서가 지정되지 않은 방식으로 쓰기 (write) 작업을 수행하도록 지시할 수 있습니다. 순서가 지정되지 않은 옵션을 사용할 때 오류가 발생하는 작업은 운전자 대량 쓰기 (write) 작업에서 다른 쓰기 (write) 작업을 실행 것을 막지 않습니다.

다음 코드는 ClientBulkWriteOptions 인스턴스 에서 ordered 옵션을 false 로 설정하고 대량 쓰기 (write) 작업을 수행하여 여러 문서를 삽입합니다.

val namespace = MongoNamespace("sample_restaurants", "restaurants")
val options = ClientBulkWriteOptions
.clientBulkWriteOptions()
.ordered(false)
val bulkOps = listOf(
ClientNamespacedWriteModel.insertOne(
namespace,
Document("_id", 1).append("name", "Freezyland")
),
// Causes a duplicate key error
ClientNamespacedWriteModel.insertOne(
namespace,
Document("_id", 1).append("name", "Coffee Stand No. 1")
),
ClientNamespacedWriteModel.insertOne<Any>(
namespace,
Document("name", "Kelly's Krepes")
)
)
val result = mongoClient
.bulkWrite(bulkOps, options)

중복 키가 있는 문서 삽입하는 쓰기 (write) 작업으로 인해 오류가 발생하더라도 쓰기 (write) 작업이 순서가 지정되지 않았으므로 다른 작업은 수행됩니다.

개별 쓰기 작업을 수행하는 방법을 알아보려면 다음 가이드를 참조하세요.

  • 문서 삽입

  • 문서 업데이트

  • 문서 삭제

  • 문서 교체

이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

삭제

이 페이지의 내용