개요
이 가이드에서는 대량 작업을 사용하는 방법에 대해 설명합니다.
대량 작업은 다수의 쓰기 작업을 수행합니다. 대량 작업은 데이터베이스에 대한 각각의 작업을 호출하는 대신 한 번의 호출로 여러 작업을 수행합니다.
샘플 데이터
이 가이드의 예시에서는 다음 Book 구조체를 books collection의 문서 모델로 사용합니다.
type Book struct { Title string Author string Length int32 }
이 가이드의 예시를 실행하려면 다음 스니펫을 사용하여 샘플 데이터를 db.books collection에 로드하세요.
coll := client.Database("db").Collection("books") docs := []interface{}{ Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331}, Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103}, } result, err := coll.InsertMany(context.TODO(), docs)
각 문서에는 각 문서의 title, author, length 필드에 해당하는 제목, 저자 및 페이지 길이가 포함된 책에 대한 설명이 포함되어 있습니다.
팁
존재하지 않는 데이터베이스 및 collection
쓰기 작업을 수행할 때 필요한 데이터베이스 및 collection이 없는 경우 서버는 이를 암시적으로 생성합니다.
대량 쓰기
대량 작업을 수행하려면 WriteModel 문서 배열 을 BulkWrite() 메서드에 전달합니다.
동작 수정
BulkWrite() 메서드는 선택적으로 BulkWriteOptions 유형을 사용하며, 이는 동작을 수정하는 데 사용할 수 있는 옵션입니다. BulkWriteOptions를 지정하지 않으면 드라이버는 각 옵션의 기본값을 사용합니다.
BulkWriteOptions 유형을 사용하면 다음 방법으로 옵션을 구성할 수 있습니다.
메서드 | 설명 |
|---|---|
| Whether to allow the write to opt-out of document level validation. Default: false |
| Whether to stop performing write operations after an error occurs. Default: true |
Return Values
성공적인 경우 BulkWrite() 메서드는 대량 작업에 대한 정보를 포함하는 BulkWriteResult 유형을 반환합니다. BulkWriteResult 유형에는 다음과 같은 속성이 포함되어 있습니다.
운영
WriteModel은 삽입, 대체, 업데이트 또는 삭제 작업을 나타냅니다.
Insert
삽입 작업을 수행하려면 삽입하려는 문서를 지정하는 InsertOneModel을 만듭니다. 여러 문서를 삽입하려면 삽입하려는 각 문서에 대해 InsertOneModel을 만듭니다.
InsertOneModel을 사용하면 다음 메서드를 사용하여 동작을 지정할 수 있습니다.
메서드 | 설명 |
|---|---|
| The document to insert. |
예시
다음 예에서는 두 개의 문서를 삽입하기 위해 두 개의 InsertOneModel 인스턴스를 만듭니다.
models := []mongo.WriteModel{ mongo.NewInsertOneModel().SetDocument(Book{Title: "Beloved", Author: "Toni Morrison", Length: 324}), mongo.NewInsertOneModel().SetDocument(Book{Title: "Outline", Author: "Rachel Cusk", Length: 258}), }
바꾸기
대체 작업을 수행하려면 대체하려는 문서와 대체 문서를 지정하는 ReplaceOneModel을 만듭니다. 여러 문서를 대체하려면 대체하려는 각 문서에 대해 ReplaceOneModel을 만듭니다.
ReplaceOneModel에서는 다음 메서드를 사용하여 동작을 지정할 수 있습니다.
메서드 | 설명 |
|---|---|
| The type of language collation to use when sorting results. |
| The query filter specifying which document to replace. |
| The index to use to scan for documents. |
| The document to replace the matched document with. |
| Whether to insert a new document if the query filter doesn't match any documents. |
예시
다음 예에서는 title이 'Lucy'인 문서를 새 문서로 대체하기 위해 ReplaceOneModel을 만듭니다.
models := []mongo.WriteModel{ mongo.NewReplaceOneModel().SetFilter(bson.D{{"title", "Lucy"}}). SetReplacement(Book{Title: "On Beauty", Author: "Zadie Smith", Length: 473}), }
Update
업데이트 작업을 수행하려면 업데이트할 문서와 문서 업데이트를 지정하는 UpdateOneModel을 만듭니다. 여러 문서를 업데이트하려면 UpdateManyModel을 사용합니다.
UpdateOneModel 및 UpdateManyModel을 사용하면 다음 메서드를 통해 동작을 지정할 수 있습니다.
메서드 | 설명 |
|---|---|
| The array elements the update applies to. |
| The type of language collation to use when sorting results. |
| The query filter specifying which document to update. |
| The index to use to scan for documents. |
| The modifications to apply on the matched documents. |
| Whether to insert a new document if the query filter doesn't match any documents. |
예시
다음 예에서는 author가 'Elena Ferrante'인 경우 문서의 length를 15만큼 줄이는 UpdateOneModel을 만듭니다.
models := []mongo.WriteModel{ mongo.NewUpdateOneModel().SetFilter(bson.D{{"author", "Elena Ferrante"}}). SetUpdate(bson.D{{"$inc", bson.D{{"length", -15}}}}), }
삭제
삭제 작업을 수행하려면 삭제하려는 문서를 지정하는 DeleteOneModel을 만듭니다. 여러 문서를 삭제하려면 DeleteManyModel을 사용합니다
DeleteOneModel 및 DeleteManyModel을 사용하면 다음 메서드를 통해 동작을 지정할 수 있습니다.
메서드 | 설명 |
|---|---|
| The type of language collation to use when sorting results. |
| The query filter specifying which document to delete. |
| The index to use to scan for documents. |
예시
다음 예에서는 length가 300보다 큰 문서를 삭제하기 위해 DeleteManyModel을 만듭니다.
models := []mongo.WriteModel{ mongo.NewDeleteManyModel().SetFilter(bson.D{{"length", bson.D{{"$gt", 300}}}}), }
실행 순서
BulkWrite() 메서드를 사용하면 BulkWriteOptions에서 대량 작업을 순서가 지정된 대로 실행할지 아니면 순서가 지정되지 않은 상태로 실행할지 지정할 수 있습니다.
순서 지정됨
기본적으로 BulkWrite() 메서드는 추가된 순서대로 대량 작업을 실행하고 오류가 발생하면 중지합니다.
팁
이는 SetOrdered() 메서드에 true로 지정하는 것과 같은 효과를 냅니다.
opts := options.BulkWrite().SetOrdered(true)
순서 지정되지 않음
대량 쓰기 작업을 임의의 순서로 실행하고 오류가 발생해도 계속 진행하려면 SetOrdered() 메서드에 false를 지정합니다. 그러면 이 메서드가 나중에 오류를 보고합니다.
예시
다음 예에서는 아래 조치를 순서와 상관없이 수행합니다.
두 개의 문서를 삽입합니다.
title이 'My Brilliant Friend'인 문서를 새 문서로 대체합니다.현재
length값이200보다 작으면 모든 문서의length를10씩 증가시킵니다.author필드 값에 'Jam'이 포함된 모든 문서를 삭제합니다.
models := []mongo.WriteModel{ mongo.NewInsertOneModel().SetDocument(Book{Title: "Middlemarch", Author: "George Eliot", Length: 904}), mongo.NewInsertOneModel().SetDocument(Book{Title: "Pale Fire", Author: "Vladimir Nabokov", Length: 246}), mongo.NewReplaceOneModel().SetFilter(bson.D{{"title", "My Brilliant Friend"}}). SetReplacement(Book{Title: "Atonement", Author: "Ian McEwan", Length: 351}), mongo.NewUpdateManyModel().SetFilter(bson.D{{"length", bson.D{{"$lt", 200}}}}). SetUpdate(bson.D{{"$inc", bson.D{{"length", 10}}}}), mongo.NewDeleteManyModel().SetFilter(bson.D{{"author", bson.D{{"$regex", "Jam"}}}}), } opts := options.BulkWrite().SetOrdered(false) results, err := coll.BulkWrite(context.TODO(), models, opts) if err != nil { panic(err) } fmt.Printf("Number of documents inserted: %d\n", results.InsertedCount) fmt.Printf("Number of documents replaced or updated: %d\n", results.ModifiedCount) fmt.Printf("Number of documents deleted: %d\n", results.DeletedCount)
Number of documents inserted: 2 Number of documents replaced or updated: 2 Number of documents deleted: 1
다음 문서는 대량 작업 후 books 컬렉션에 포함됩니다.
{"title":"Atonement","author":"Ian McEwan","length":351} {"title":"Middlemarch","author":"George Eliot","length":904} {"title":"Pale Fire","author":"Vladimir Nabokov","length":246}
추가 정보
언급된 작업을 수행하는 방법에 대해 자세히 알아보려면 다음 가이드를 참조하세요:
API 문서
이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.