Docs Menu
Docs Home
/ / /
Go 드라이버
/ / /

대량 작업

이 가이드 에서는 MongoDB 고 (Go) 드라이버 사용하여 대량 작업을 수행하는 방법을 학습 수 있습니다. 대량 작업은 단일 메서드로 여러 쓰기 (write) 작업을 수행하여 서버 에 대한 호출 수를 줄입니다.

CollectionClient 클래스는 모두 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
}

이 가이드 의 예제를 실행 하려면 다음 스니펫을 사용하여 샘플 데이터를 bookspoems 컬렉션 에 로드합니다.

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 을 만듭니다.

대량 쓰기 (write) 에 대한 삽입 작업을 정의하려면 삽입하려는 문서 지정하는 InsertOneModel 을 만듭니다. 여러 문서를 삽입하려면 삽입하려는 각 문서 에 대해 InsertOneModel 을 만듭니다.

다음 메서드를 사용하여 InsertOneModel 의 동작을 지정할 수 있습니다.

메서드
설명

SetDocument()

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}),
}

대량 쓰기 (write) 에 대한 대체 작업을 정의하려면 대체하려는 문서 와 대체 문서 지정하는 ReplaceOneModel 를 만듭니다. 여러 문서를 대체하려면 대체하려는 각 문서 에 대해 ReplaceOneModel 을 만듭니다.

다음 메서드를 사용하여 ReplaceOneModel 의 동작을 지정할 수 있습니다.

메서드
설명

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to replace.

SetHint()

The index to use to scan for documents.

SetReplacement()

The document to replace the matched document with.

SetSort()

The sort order for matching documents. The replace operation replaces only the first document according to the sort criteria.

SetUpsert()

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}),
}

대량 쓰기 (write) 에 대한 업데이트 작업을 정의하려면 업데이트 하려는 문서 와 업데이트 문서 지정하는 UpdateOneModel 을 만듭니다. 여러 문서를 업데이트 하려면 UpdateManyModel을 사용합니다.

다음 메서드를 사용하여 각 업데이트 모델의 동작을 지정할 수 있습니다.

메서드
설명

SetArrayFilters()

The array elements the update applies to.

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to update.

SetHint()

The index to use to scan for documents.

SetSort()

The criteria to use when ordering matching documents. This method is only available for the UpdateOneModel class.

SetUpdate()

The modifications to apply on the matched documents.

SetUpsert()

Whether to insert a new document if the query filter doesn't match any documents.

다음 예시 에서는 books 컬렉션 의 문서 업데이트 위해 author"Elena Ferrante"인 경우 문서의 length15 만큼 감소시키는 UpdateOneModel 를 생성합니다.

models := []mongo.WriteModel{
mongo.NewUpdateOneModel().SetFilter(bson.D{{"author", "Elena Ferrante"}}).
SetUpdate(bson.D{{"$inc", bson.D{{"length", -15}}}}),
}

대량 쓰기 (write) 에 대한 삭제 작업을 정의하려면 삭제 하려는 문서 지정하는 DeleteOneModel 을 만듭니다. 여러 문서를 삭제 하려면 DeleteManyModel을 사용합니다.

다음 메서드를 사용하여 각 삭제 모델의 동작을 지정할 수 있습니다.

메서드
설명

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to delete.

SetHint()

The index to use to scan for documents.

다음 예시 에서는 books 컬렉션 에서 length300보다 큰 문서를 삭제 위해 DeleteManyModel 을 만듭니다.

models := []mongo.WriteModel{
mongo.NewDeleteManyModel().SetFilter(bson.D{{"length", bson.D{{"$gt", 300}}}}),
}

대량 쓰기 (write) 작업의 동작을 수정하려면 BulkWriteOptions 인스턴스 BulkWrite() 메서드에 전달합니다.

BulkWriteOptions 유형을 사용하면 다음 메서드를 사용하여 옵션을 구성할 수 있습니다.

메서드
설명

SetBypassDocumentValidation()

Specifies whether the operation can opt-out of document level validation.
Default: false

SetComment()

Specifies a comment to attach to the operation.
Default: nil

SetLet()

Specifies a document with a list of values to improve operation readability. Values must be constant or closed expressions that don't reference document fields. For more information, see the let field for the delete and update commands in the MongoDB Server manual.
Default: nil

SetOrdered()

Specifies whether the driver stops performing write operations after an error occurs.
Default: true

BulkWrite() 메서드는 대량 작업에 대한 정보가 포함된 BulkWriteResult 유형을 반환합니다.

BulkWriteResult 유형에는 다음과 같은 속성이 포함되어 있습니다.

속성
설명

InsertedCount

삽입된 문서 수입니다.

MatchedCount

업데이트 및 대체 작업에서 쿼리 필터와 일치하는 문서 수입니다.

ModifiedCount

업데이트 및 대체 작업에 의해 수정된 문서 수입니다.

DeletedCount

삭제된 문서 수입니다.

UpsertedCount

업데이트 및 대체 작업에 의해 업서트된 문서 수입니다.

UpsertedIDs

업서트된 각 문서의 _id에 대한 작업 인덱스 맵입니다.

Acknowledged

쓰기 (write) 작업이 승인되었는지 여부를 나타내는 부울 값입니다.

대량 쓰기 (write) 작업을 순서대로 수행할지 여부를 지정하려면 Ordered 옵션을 부울 값으로 설정하다 됩니다. 이 옵션을 설정하다 하려면 BulkWriteOptions 인스턴스 의 Ordered 필드 지정합니다.

기본값 으로 BulkWrite() 메서드는 대량 작업을 추가한 순서대로 실행하고 오류가 발생하면 중지합니다.

이는 다음 코드에 표시된 대로 SetOrdered() 메서드에 true 값을 전달하는 것과 같습니다.

opts := options.BulkWrite().SetOrdered(true)

대량 쓰기 (write) 작업을 임의의 순서로 실행 하고 오류가 발생해도 계속 진행하려면 SetOrdered() 메서드에 false 값을 전달합니다. 이 메서드는 작업이 완료된 후 오류를 보고합니다.

다음 예에서는 아래 조치를 순서와 상관없이 수행합니다.

  • 두 개의 문서를 삽입합니다.

  • title 이 'My Brilliant Friend'인 문서 새 문서 로 교체합니다.

  • 현재 length 값이 200보다 작으면 모든 문서의 length10 만큼 증가시킵니다.

  • 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>},
...
}

대량 쓰기 (write) 에 대한 삽입 작업을 정의하려면 삽입하려는 문서 지정하는 ClientInsertOneModel 을 만듭니다. 여러 문서를 삽입하려면 삽입하려는 각 문서 에 대해 ClientInsertOneModel 을 만듭니다.

다음 메서드를 사용하여 ClientInsertOneModel 의 동작을 지정할 수 있습니다.

메서드
설명

SetDocument()

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)},
}

대량 쓰기 (write) 에 대한 대체 작업을 정의하려면 대체하려는 ClientReplaceOneModel 문서 와 대체 문서 지정하는 를 만듭니다. 여러 문서를 대체하려면 대체하려는 각 문서 ClientReplaceOneModel 에 대해 을 만듭니다.

다음 메서드를 사용하여 ClientReplaceOneModel 의 동작을 지정할 수 있습니다.

메서드
설명

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to replace.

SetHint()

The index to use to scan for documents.

SetReplacement()

The document to replace the matched document with.

SetSort()

The sort order for matching documents. The replace operation replaces only the first document according to the sort criteria.

SetUpsert()

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})},
}

대량 쓰기 (write) 에 대한 업데이트 작업을 정의하려면 업데이트 ClientUpdateOneModel 하려는 문서 와 업데이트 문서 지정하는 를 만듭니다. 여러 문서를 업데이트 하려면 을 사용합니다.ClientUpdateManyModel

다음 메서드를 사용하여 각 업데이트 모델의 동작을 지정할 수 있습니다.

메서드
설명

SetArrayFilters()

The array elements the update applies to.

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to update.

SetHint()

The index to use to scan for documents.

SetSort()

The criteria to use when ordering matching documents. This method is only available for the ClientUpdateOneModel class.

SetUpdate()

The modifications to apply on the matched documents.

SetUpsert()

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 인스턴스를 사용합니다.

대량 쓰기 (write) 에 대한 삭제 작업을 정의하려면 삭제 하려는 문서 지정하는 ClientDeleteOneModel 을 만듭니다. 여러 문서를 삭제 하려면 ClientDeleteManyModel을 사용합니다.

다음 메서드를 사용하여 각 삭제 모델의 동작을 지정할 수 있습니다.

메서드
설명

SetCollation()

The type of language collation to use when sorting results.

SetFilter()

The query filter specifying which document to delete.

SetHint()

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 유형을 사용하면 다음 메서드를 사용하여 옵션을 구성할 수 있습니다.

메서드
설명

SetBypassDocumentValidation()

Specifies whether the operation can opt-out of document level validation.
Default: false

SetOrdered()

Specifies whether the driver stops performing write operations after an error occurs.
Default: true

SetComment()

Specifies a comment to attach to the operation.
Default: nil

SetLet()

Specifies a document with a list of values to improve operation readability. Values must be constant or closed expressions that don't reference document fields. For more information, see the let field for the delete and update commands in the MongoDB Server manual.
Default: nil

SetWriteConcern()

Specifies the write concern for the operations.
Default: nil

SetVerboseResults()

Specifies whether detailed information about each successful operation is included in the result.
Default: false

BulkWrite() 메서드는 대량 작업에 대한 정보가 포함된 ClientBulkWriteResult 유형을 반환합니다.

ClientBulkWriteResult 유형에는 다음과 같은 속성이 포함되어 있습니다.

속성
설명

InsertedCount

삽입된 문서 수입니다.

MatchedCount

업데이트 및 대체 작업에서 쿼리 필터와 일치하는 문서 수입니다.

ModifiedCount

업데이트 및 대체 작업에 의해 수정된 문서 수입니다.

DeletedCount

삭제된 문서 수입니다.

UpsertedCount

업데이트 및 대체 작업에 의해 업서트된 문서 수입니다.

InsertResults

삽입된 각 문서 의 _id 값에 대한 작업 인덱스 의 맵입니다.

UpdateResults

업데이트된 각 문서 의 _id 값에 대한 작업 인덱스 의 맵입니다.

DeleteResults

삭제된 각 문서 의 _id 값에 대한 작업 인덱스 의 맵입니다.

Acknowledged

쓰기 (write) 작업이 승인되었는지 여부를 나타내는 부울 값입니다.

HasVerboseResults

결과에 자세한 결과가 포함되어 있는지 여부를 나타내는 부울 값입니다.

대량 쓰기 (write) 작업을 순서대로 수행할지 여부를 지정하려면 Ordered 옵션을 부울 값으로 설정하다 됩니다. 이 옵션을 설정하다 하려면 ClientBulkWriteOptions 인스턴스 의 Ordered 필드 지정합니다.

기본적으로 BulkWrite() 메서드는 추가된 순서대로 대량 작업을 실행하고 오류가 발생하면 중지합니다.

이는 다음 코드에 표시된 대로 SetOrdered() 메서드에 true 값을 전달하는 것과 같습니다.

opts := options.ClientBulkWrite().SetOrdered(true)

대량 쓰기 (write) 작업을 임의의 순서로 실행 하고 오류가 발생해도 계속 진행하려면 SetOrdered() 메서드에 false 값을 전달합니다. 이 메서드는 작업이 완료된 후 오류를 보고합니다.

다음 예에서는 아래 조치를 순서와 상관없이 수행합니다.

  • bookspoems 컬렉션에 새 문서 삽입합니다.

  • 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 문서