대량 작업
개요
이 가이드 에서는 MongoDB 고 (Go) 드라이버 사용하여 대량 작업을 수행하는 방법을 학습 수 있습니다. 대량 작업은 단일 메서드로 여러 쓰기 (write) 작업을 수행하여 서버 에 대한 호출 수를 줄입니다.
Collection
및 Client
클래스는 모두 BulkWrite()
메서드를 제공합니다. Collection.BulkWrite()
메서드를 사용하여 단일 컬렉션 에 대해 여러 쓰기 (write) 작업을 수행할 수 있습니다. Client.BulkWrite()
메서드를 사용하여 여러 네임스페이스에 걸쳐 대량 쓰기를 수행할 수 있습니다. MongoDB 에서 네임스페이스 데이터베이스 이름과 컬렉션 이름으로 구성됩니다.
중요
클라이언트 대량 쓰기 서버 요구 사항
Client
인스턴스 에서 대량 작업을 수행하려면 애플리케이션 MongoDB Server v8.0 이상에 연결되어 있어야 합니다.
샘플 데이터
이 가이드 의 예제에서는 다음 구조체를 사용합니다.
Book
구조체는db.books
컬렉션 의 문서를 모델링합니다. 각 문서 에는 제목, 저자, 페이지 길이를 포함한 책에 대한 설명이 포함되어 있습니다.Poem
구조체는db.poems
컬렉션 의 문서를 모델링합니다. 각 문서 에는 제목, 저자, 발행 연도가 포함된 시 설명이 포함되어 있습니다.
type Book struct { Title string Author string Length int32 } type Poem struct { Title string Author string Year int32 }
이 가이드 의 예제를 실행 하려면 다음 스니펫을 사용하여 샘플 데이터를 books
및 poems
컬렉션 에 로드합니다.
bookColl := client.Database("db").Collection("books") poemColl := client.Database("db").Collection("poems") books := []interface{}{ Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331}, Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103}, } poems := []interface{}{ Poem{Title: "Song of Myself", Author: "Walt Whitman", Year: 1855}, Poem{Title: "The Raincoat", Author: "Ada Limon", Year: 2018}, } bookInsert, err := bookColl.InsertMany(context.TODO(), books) poemInsert, err := poemColl.InsertMany(context.TODO(), poems)
팁
존재하지 않는 데이터베이스 및 collection
쓰기 작업을 수행할 때 필요한 데이터베이스 및 collection이 없는 경우 서버는 이를 암시적으로 생성합니다.
컬렉션 대량 쓰기
단일 네임스페이스 에서 대량 작업을 수행하려면 컬렉션 에서 BulkWrite()
메서드를 호출하고 WriteModel 문서의 배열 매개 변수로 전달합니다.
컬렉션 대량 쓰기 모델 정의
하나의 네임스페이스 에서 대량 작업에 대한 쓰기 (write) 작업을 정의하려면 삽입, 교체, 업데이트 또는 삭제 각각에 대해 WriteModel
을 만듭니다.
InsertOneModel
대량 쓰기 (write) 에 대한 삽입 작업을 정의하려면 삽입하려는 문서 지정하는 InsertOneModel
을 만듭니다. 여러 문서를 삽입하려면 삽입하려는 각 문서 에 대해 InsertOneModel
을 만듭니다.
다음 메서드를 사용하여 InsertOneModel
의 동작을 지정할 수 있습니다.
메서드 | 설명 |
---|---|
| The document to insert. |
다음 예시 에서는 두 개의 InsertOneModel
인스턴스를 만들어 books
컬렉션 에 두 개의 문서를 삽입합니다.
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
대량 쓰기 (write) 에 대한 대체 작업을 정의하려면 대체하려는 문서 와 대체 문서 지정하는 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. |
| The sort order for matching documents. The replace operation
replaces only the first document according to the sort criteria. |
| Whether to insert a new document if the query filter doesn't match any documents. |
다음 예시 title
값이 "Lucy"
인 books
컬렉션 의 문서 대체하기 위해 ReplaceOneModel
을 만듭니다.
models := []mongo.WriteModel{ mongo.NewReplaceOneModel().SetFilter(bson.D{{"title", "Lucy"}}). SetReplacement(Book{Title: "On Beauty", Author: "Zadie Smith", Length: 473}), }
UpdateOneModel 및 UpdateManyModel
대량 쓰기 (write) 에 대한 업데이트 작업을 정의하려면 업데이트 하려는 문서 와 업데이트 문서 지정하는 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 criteria to use when ordering matching documents.
This method is only available for the UpdateOneModel
class. |
| The modifications to apply on the matched documents. |
| Whether to insert a new document if the query filter doesn't match any documents. |
다음 예시 에서는 books
컬렉션 의 문서 업데이트 위해 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
대량 쓰기 (write) 에 대한 삭제 작업을 정의하려면 삭제 하려는 문서 지정하는 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. |
다음 예시 에서는 books
컬렉션 에서 length
가 300
보다 큰 문서를 삭제 위해 DeleteManyModel
을 만듭니다.
models := []mongo.WriteModel{ mongo.NewDeleteManyModel().SetFilter(bson.D{{"length", bson.D{{"$gt", 300}}}}), }
컬렉션 수준 동작 수정
대량 쓰기 (write) 작업의 동작을 수정하려면 BulkWriteOptions
인스턴스 BulkWrite()
메서드에 전달합니다.
BulkWriteOptions
유형을 사용하면 다음 메서드를 사용하여 옵션을 구성할 수 있습니다.
메서드 | 설명 |
---|---|
| Specifies whether the operation can opt-out of document level validation. Default: false |
| Specifies a comment to attach to the operation. Default: nil |
| |
| Specifies whether the driver stops performing write operations after an error occurs. Default: true |
컬렉션 수준 반환 값
BulkWrite()
메서드는 대량 작업에 대한 정보가 포함된 BulkWriteResult
유형을 반환합니다.
BulkWriteResult
유형에는 다음과 같은 속성이 포함되어 있습니다.
컬렉션 수준 실행 순서
대량 쓰기 (write) 작업을 순서대로 수행할지 여부를 지정하려면 Ordered
옵션을 부울 값으로 설정하다 됩니다. 이 옵션을 설정하다 하려면 BulkWriteOptions
인스턴스 의 Ordered
필드 지정합니다.
순서 지정됨
기본값 으로 BulkWrite()
메서드는 대량 작업을 추가한 순서대로 실행하고 오류가 발생하면 중지합니다.
팁
이는 다음 코드에 표시된 대로 SetOrdered()
메서드에 true
값을 전달하는 것과 같습니다.
opts := options.BulkWrite().SetOrdered(true)
순서 지정되지 않음
대량 쓰기 (write) 작업을 임의의 순서로 실행 하고 오류가 발생해도 계속 진행하려면 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"}}}}), } // Specifies that the bulk write is unordered opts := options.BulkWrite().SetOrdered(false) // Runs the bulk write operation and prints a summary of the // data changes results, err := bookColl.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}
클라이언트 대량 쓰기
여러 네임스페이스에서 일괄 작업을 수행하려면 클라이언트 에서 BulkWrite()
메서드를 호출하고 ClientWriteModel 문서 배열 매개변수로 전달합니다.
클라이언트 대량 쓰기 모델 정의
여러 네임스페이스에 대한 대량 작업에 대한 쓰기 (write) 작업을 지정하려면 삽입, 교체, 업데이트 또는 삭제 각각에 대해 ClientWriteModel
을 만듭니다. 다음 코드와 같이 각 쓰기 (write) 모델을 ClientBulkWrite
구조체에 전달하고 대상 데이터베이스 와 컬렉션 지정합니다.
writes := []mongo.ClientBulkWrite{ {"<database name>", "<collection name>", <write model>}, ... }
ClientInsertOneModel
대량 쓰기 (write) 에 대한 삽입 작업을 정의하려면 삽입하려는 문서 지정하는 ClientInsertOneModel
을 만듭니다. 여러 문서를 삽입하려면 삽입하려는 각 문서 에 대해 ClientInsertOneModel
을 만듭니다.
다음 메서드를 사용하여 ClientInsertOneModel
의 동작을 지정할 수 있습니다.
메서드 | 설명 |
---|---|
| The document to insert. |
다음 예시 두 개의 ClientInsertOneModel
인스턴스를 만들어 books
컬렉션 에 문서 하나를 삽입하고 poems
컬렉션 에 문서 하나를 삽입합니다.
bookInsertDoc := Book{Title: "Parable of the Sower", Author: "Octavia E. Butler", Length: 320} poemInsertDoc := Poem{Title: "Fame is a fickle food", Author: "Emily Dickinson", Year: 1659} writes := []mongo.ClientBulkWrite{ {"db", "books", mongo.NewClientInsertOneModel().SetDocument(bookInsertDoc)}, {"db", "poems", mongo.NewClientInsertOneModel().SetDocument(poemInsertDoc)}, }
ClientReplaceOneModel
대량 쓰기 (write) 에 대한 대체 작업을 정의하려면 대체하려는 ClientReplaceOneModel
문서 와 대체 문서 지정하는 를 만듭니다. 여러 문서를 대체하려면 대체하려는 각 문서 ClientReplaceOneModel
에 대해 을 만듭니다.
다음 메서드를 사용하여 ClientReplaceOneModel
의 동작을 지정할 수 있습니다.
메서드 | 설명 |
---|---|
| 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. |
| The sort order for matching documents. The replace operation
replaces only the first document according to the sort criteria. |
| Whether to insert a new document if the query filter doesn't match any documents. |
이 예시 ClientReplaceOneModel
인스턴스를 만들어 다음 작업을 정의합니다.
title
값이"Lucy"
인 문서 대체하는books
컬렉션 에 대한 대체 작업입니다.title
값이"Song of Myself"
인 문서 대체하는poems
컬렉션 에 대한 대체 작업입니다.
writes := []mongo.ClientBulkWrite{ {"db", "books", mongo.NewClientReplaceOneModel(). SetFilter(bson.D{{"title", "Lucy"}}). SetReplacement(Book{Title: "On Beauty", Author: "Zadie Smith", Length: 473})}, {"db", "poems", mongo.NewClientReplaceOneModel(). SetFilter(bson.D{{"title", "Song of Myself"}}). SetReplacement(Poem{Title: "America", Author: "Walt Whitman", Year: 1888})}, }
ClientUpdateOneModel 및 ClientUpdateManyModel
대량 쓰기 (write) 에 대한 업데이트 작업을 정의하려면 업데이트 ClientUpdateOneModel
하려는 문서 와 업데이트 문서 지정하는 를 만듭니다. 여러 문서를 업데이트 하려면 을 사용합니다.ClientUpdateManyModel
다음 메서드를 사용하여 각 업데이트 모델의 동작을 지정할 수 있습니다.
메서드 | 설명 |
---|---|
| 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 criteria to use when ordering matching documents.
This method is only available for the ClientUpdateOneModel class. |
| The modifications to apply on the matched documents. |
| Whether to insert a new document if the query filter
doesn't match any documents. |
이 예시 ClientUpdateOneModel
인스턴스를 만들어 다음 작업을 정의합니다.
books
컬렉션 에 대한 업데이트 작업을 수행하여author
값이"Elena Ferrante"
인 문서 업데이트 .poems
컬렉션 에 대한 업데이트 작업을 수행하여author
값이"Ada Limon"
인 문서 업데이트 .
writes := []mongo.ClientBulkWrite{ {"db", "books", mongo.NewClientUpdateOneModel(). SetFilter(bson.D{{"author", "Elena Ferrante"}}). SetUpdate(bson.D{{"$inc", bson.D{{"length", -15}}}})}, {"db", "poems", mongo.NewClientUpdateOneModel(). SetFilter(bson.D{{"author", "Ada Limon"}}). SetUpdate(bson.D{{"author", "Ada Limón"}})}, }
참고
앞의 예시 author
필드 쿼리 필터와 일치하는 모든 문서를 업데이트 하려면 ClientUpdateManyModel
인스턴스를 사용합니다.
ClientDeleteOneModel 및 ClientDeleteManyModel
대량 쓰기 (write) 에 대한 삭제 작업을 정의하려면 삭제 하려는 문서 지정하는 ClientDeleteOneModel
을 만듭니다. 여러 문서를 삭제 하려면 ClientDeleteManyModel
을 사용합니다.
다음 메서드를 사용하여 각 삭제 모델의 동작을 지정할 수 있습니다.
메서드 | 설명 |
---|---|
| 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. |
이 예시 ClientDeleteOneModel
인스턴스를 만들어 다음 작업을 정의합니다.
length
값이103
인 문서 삭제 하는books
컬렉션 에 대한 삭제 작업입니다.year
값이1855
인 문서 삭제 하는poems
컬렉션 에 대한 삭제 작업입니다.
writes := []mongo.ClientBulkWrite{ {"db", "books", mongo.NewClientDeleteOneModel(). SetFilter(bson.D{{"length", 103}})}, {"db", "poems", mongo.NewClientDeleteOneModel(). SetFilter(bson.D{{"year", 1855}})}, }
클라이언트 수준 동작 수정
대량 쓰기 (write) 작업의 동작을 수정하려면 ClientBulkWriteOptions
인스턴스 BulkWrite()
메서드에 전달합니다.
ClientBulkWriteOptions
유형을 사용하면 다음 메서드를 사용하여 옵션을 구성할 수 있습니다.
메서드 | 설명 |
---|---|
| Specifies whether the operation can opt-out of document level validation. Default: false |
| Specifies whether the driver stops performing write operations after an error occurs. Default: true |
| Specifies a comment to attach to the operation. Default: nil |
| |
| Specifies the write concern for the operations. Default: nil |
| Specifies whether detailed information about each successful operation is
included in the result. Default: false |
클라이언트 수준 반환 값
BulkWrite()
메서드는 대량 작업에 대한 정보가 포함된 ClientBulkWriteResult
유형을 반환합니다.
ClientBulkWriteResult
유형에는 다음과 같은 속성이 포함되어 있습니다.
속성 | 설명 |
---|---|
| 삽입된 문서 수입니다. |
| 업데이트 및 대체 작업에서 쿼리 필터와 일치하는 문서 수입니다. |
| 업데이트 및 대체 작업에 의해 수정된 문서 수입니다. |
| 삭제된 문서 수입니다. |
| 업데이트 및 대체 작업에 의해 업서트된 문서 수입니다. |
| 삽입된 각 문서 의 |
| 업데이트된 각 문서 의 |
| 삭제된 각 문서 의 |
| 쓰기 (write) 작업이 승인되었는지 여부를 나타내는 부울 값입니다. |
| 결과에 자세한 결과가 포함되어 있는지 여부를 나타내는 부울 값입니다. |
클라이언트 수준 실행 순서
대량 쓰기 (write) 작업을 순서대로 수행할지 여부를 지정하려면 Ordered
옵션을 부울 값으로 설정하다 됩니다. 이 옵션을 설정하다 하려면 ClientBulkWriteOptions
인스턴스 의 Ordered
필드 지정합니다.
순서 지정됨
기본적으로 BulkWrite()
메서드는 추가된 순서대로 대량 작업을 실행하고 오류가 발생하면 중지합니다.
팁
이는 다음 코드에 표시된 대로 SetOrdered()
메서드에 true
값을 전달하는 것과 같습니다.
opts := options.ClientBulkWrite().SetOrdered(true)
순서 지정되지 않음
대량 쓰기 (write) 작업을 임의의 순서로 실행 하고 오류가 발생해도 계속 진행하려면 SetOrdered()
메서드에 false
값을 전달합니다. 이 메서드는 작업이 완료된 후 오류를 보고합니다.
다음 예에서는 아래 조치를 순서와 상관없이 수행합니다.
books
및poems
컬렉션에 새 문서 삽입합니다.poems
컬렉션 에서title
값이"The Raincoat"
인 문서 업데이트합니다.books
컬렉션 에서title
값이"My Brilliant Friend"
인 문서 대체합니다.
writes := []mongo.ClientBulkWrite{ {"db", "books", mongo.NewClientInsertOneModel(). SetDocument(Book{Title: "Middlemarch", Author: "George Eliot", Length: 904})}, {"db", "poems", mongo.NewClientInsertOneModel(). SetDocument(Poem{Title: "Mad Girl's Love Song", Author: "Sylvia Plath", Year: 1953})}, {"db", "poems", mongo.NewClientUpdateOneModel(). SetFilter(bson.D{{"title", "The Raincoat"}}). SetUpdate(bson.D{{"title", "The Conditional"}})}, {"db", "books", mongo.NewClientReplaceOneModel(). SetFilter(bson.D{{"title", "My Brilliant Friend"}}). SetReplacement(Book{Title: "The Story of a New Name", Author: "Elena Ferrante", Length: 480})}, } opts := options.ClientBulkWrite().SetOrdered(false) results, err := client.BulkWrite(context.TODO(), writes, 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)
Number of documents inserted: 2 Number of documents replaced or updated: 2
추가 정보
대량 작업에 실행 가능한 예시를 보려면 대량 작업 수행을 참조하세요.
관련 작업
언급된 작업을 수행하는 방법에 대해 자세히 알아보려면 다음 가이드를 참조하세요:
API 문서
컬렉션 대량 쓰기에 사용되는 메서드 또는 유형에 대해 자세히 학습 다음 API 설명서를 참조하세요.
클라이언트 대량 쓰기에 사용되는 메서드 또는 유형에 대해 자세히 학습 다음 API 설명서를 참조하세요.