AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Make the MongoDB docs better! We value your opinion. Share your feedback for a chance to win $100.
MongoDB Branding Shape
Click here >
Docs Menu

대량 작업

이 가이드 에서는 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 := []any{
Book{Title: "My Brilliant Friend", Author: "Elena Ferrante", Length: 331},
Book{Title: "Lucy", Author: "Jamaica Kincaid", Length: 103},
}
poems := []any{
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()

삽입할 문서입니다.

다음 예시 에서는 두 개의 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()

결과를 정렬할 때 사용할 언어 데이터 정렬 유형입니다.

SetFilter()

대체할 문서를 지정하는 쿼리 필터입니다.

SetHint()

문서를 스캔할 때 사용할 인덱스입니다.

SetReplacement()

일치하는 문서를 대체할 문서입니다.

SetSort()

일치하는 문서의 정렬 순서입니다. 대체 작업은 정렬 기준에 따라 첫 번째 문서 만 대체합니다.

SetUpsert()

쿼리 필터가 문서와 일치하지 않는 경우 새 문서를 삽입할지 여부를 지정합니다.

다음 예시 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()

업데이트가 적용되는 배열 요소입니다.

SetCollation()

결과를 정렬할 때 사용할 언어 데이터 정렬 유형입니다.

SetFilter()

업데이트할 문서를 지정하는 쿼리 필터입니다.

SetHint()

문서를 스캔할 때 사용할 인덱스입니다.

SetSort()

일치하는 문서를 주문할 때 사용할 기준입니다. 이 메서드는 UpdateOneModel 클래스에만 사용할 수 있습니다.

SetUpdate()

일치하는 문서에 적용할 수정 사항입니다.

SetUpsert()

쿼리 필터가 문서와 일치하지 않는 경우 새 문서를 삽입할지 여부를 지정합니다.

다음 예시 에서는 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()

결과를 정렬할 때 사용할 언어 데이터 정렬 유형입니다.

SetFilter()

삭제할 문서를 지정하는 쿼리 필터입니다.

SetHint()

문서를 스캔할 때 사용할 인덱스입니다.

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

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

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

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

메서드
설명

SetBypassDocumentValidation()

작업에서 문서 수준 유효성 검사 옵트아웃할 수 있는지 여부를 지정합니다.
기본값: false

SetComment()

작업에 첨부할 주석을 지정합니다.
기본값: nil

SetLet()

작업 가독성을 높이기 위해 값 목록이 포함된 문서 지정합니다. 값은 문서 필드를 참조하지 않는 상수 또는 닫힌 표현식이어야 합니다. 자세한 let 내용은 MongoDB Server 매뉴얼에서 삭제업데이트 명령에 대한 필드 참조하세요.
기본값: nil

SetOrdered()

오류가 발생한 후 운전자 쓰기 (write) 작업 수행을 중지할지 여부를 지정합니다.
기본값: 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}

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants 데이터베이스restaurants 컬렉션도 사용합니다. Atlas 시작하기의 단계에 따라 MongoDB Atlas의 무료 계층에서 데이터베이스에 로드할 수 있습니다.

다음 예시 다음 조치를 수행하는 완전히 실행 가능한 파일 입니다.

  • name 필드 값이 "Towne Cafe" 인 문서 일치시키고 name 필드 값이 "New Towne Cafe" 로, cuisine 필드 값이 "French"설정하다 설정하다 문서 로 바꿉니다.

  • name 필드 값이 Riviera Caterer 인 문서 일치시키고 name 필드 값을 "Riviera Cafe"로 업데이트합니다.

// Runs bulk write operations on a collection by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Defines a Restaurant struct as a model for documents in the "restaurants" collection
type Restaurant struct {
Name string
RestaurantId string `bson:"restaurant_id,omitempty"`
Cuisine string `bson:"cuisine,omitempty"`
Address any `bson:"address,omitempty"`
Borough string `bson:"borough,omitempty"`
Grades []any `bson:"grades,omitempty"`
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
// Creates write models that specify replace and update operations
models := []mongo.WriteModel{
mongo.NewReplaceOneModel().SetFilter(bson.D{{"name", "Towne Cafe"}}).
SetReplacement(Restaurant{Name: "New Towne Cafe", Cuisine: "French"}),
mongo.NewUpdateOneModel().SetFilter(bson.D{{"name", "Riviera Caterer"}}).
SetUpdate(bson.D{{"$set", bson.D{{"name", "Riviera Cafe"}}}}),
}
// Specifies that the bulk write is ordered
opts := options.BulkWrite().SetOrdered(true)
// Runs a bulk write operation for the specified write operations
results, err := coll.BulkWrite(context.TODO(), models, opts)
if err != nil {
panic(err)
}
// When you run this file for the first time, it should print output similar to the following:
// Number of documents replaced or modified: 2
fmt.Printf("Number of documents replaced or modified: %d", results.ModifiedCount)
}
Number of documents matched: 2
Number of documents modified: 2

여러 네임스페이스에서 일괄 작업을 수행하려면 클라이언트 에서 BulkWrite() 메서드를 호출하고 ClientWriteModel 문서 배열 매개변수로 전달합니다.

여러 네임스페이스에 대한 대량 작업에 대한 쓰기 (write) 작업을 지정하려면 삽입, 교체, 업데이트 또는 삭제 각각에 대해 ClientWriteModel 을 만듭니다. 다음 코드와 같이 각 쓰기 (write) 모델을 ClientBulkWrite 구조체에 전달하고 대상 데이터베이스 와 컬렉션 지정합니다.

writes := []mongo.ClientBulkWrite{
{"<database name>", "<collection name>", <write model>},
...
}

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

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

메서드
설명

SetDocument()

삽입할 문서입니다.

다음 예시 두 개의 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()

결과를 정렬할 때 사용할 언어 데이터 정렬 유형입니다.

SetFilter()

대체할 문서를 지정하는 쿼리 필터입니다.

SetHint()

문서를 스캔할 때 사용할 인덱스입니다.

SetReplacement()

일치하는 문서를 대체할 문서입니다.

SetSort()

일치하는 문서의 정렬 순서입니다. 대체 작업은 정렬 기준에 따라 첫 번째 문서 만 대체합니다.

SetUpsert()

쿼리 필터가 문서와 일치하지 않는 경우 새 문서를 삽입할지 여부를 지정합니다.

이 예시 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()

업데이트가 적용되는 배열 요소입니다.

SetCollation()

결과를 정렬할 때 사용할 언어 데이터 정렬 유형입니다.

SetFilter()

업데이트할 문서를 지정하는 쿼리 필터입니다.

SetHint()

문서를 스캔할 때 사용할 인덱스입니다.

SetSort()

일치하는 문서를 주문할 때 사용할 기준입니다. 이 메서드는 ClientUpdateOneModel 클래스에만 사용할 수 있습니다.

SetUpdate()

일치하는 문서에 적용할 수정 사항입니다.

SetUpsert()

쿼리 필터가 문서와 일치하지 않는 경우 새 문서를 삽입할지 여부를 지정합니다.

이 예시 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()

결과를 정렬할 때 사용할 언어 데이터 정렬 유형입니다.

SetFilter()

삭제할 문서를 지정하는 쿼리 필터입니다.

SetHint()

문서를 스캔할 때 사용할 인덱스입니다.

이 예시 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()

작업에서 문서 수준 유효성 검사 옵트아웃할 수 있는지 여부를 지정합니다.
기본값: false

SetOrdered()

오류가 발생한 후 운전자 쓰기 (write) 작업 수행을 중지할지 여부를 지정합니다.
기본값: true

SetComment()

작업에 첨부할 주석을 지정합니다.
기본값: nil

SetLet()

작업 가독성을 높이기 위해 값 목록이 포함된 문서 지정합니다. 값은 문서 필드를 참조하지 않는 상수 또는 닫힌 표현식이어야 합니다. 자세한 let 내용은 MongoDB Server 매뉴얼에서 삭제업데이트 명령에 대한 필드 참조하세요.
기본값: nil

SetWriteConcern()

작업에 대한 쓰기 고려 (write concern) 지정합니다.
기본값: nil

SetVerboseResults()

성공적인 각 작업에 대한 자세한 정보를 결과에 포함할지 여부를 지정합니다.
기본값: 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 설명서를 참조하세요.