문서 메뉴

문서 홈애플리케이션 개발MongoDB 드라이버Go 드라이버

대량 작업 수행

BulkWrite() 메서드를 사용하여 컬렉션에 대량 쓰기 작업을 수행할 수 있습니다.

Read the Usage Examples to learn how to run this example.

이 예제에서는 restaurants 컬렉션의 문서에 대한 모델로 다음 Restaurant 구조체를 사용합니다:

type Restaurant struct {
Name string
RestaurantId string `bson:"restaurant_id,omitempty"`
Cuisine string `bson:"cuisine,omitempty"`
Address interface{} `bson:"address,omitempty"`
Borough string `bson:"borough,omitempty"`
Grades []interface{} `bson:"grades,omitempty"`
}

omitempty struct 태그 는 비어 있을 때 삽입된 문서에서 해당 필드를 생략합니다.

다음 예시에서는 restaurants 컬렉션에서 다음 작업을 순서대로 수행합니다.

  • name이 "Cafe Tomato"인 문서를 일치시키고 새 문서로 바꿉니다.

  • name이 "Cafe Zucchini"인 문서와 일치시키고 값을 "Zucchini Land"로 업데이트합니다.

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", "Cafe Tomato"}}).
SetReplacement(Restaurant{Name: "Cafe Zucchini", Cuisine: "French"}),
mongo.NewUpdateOneModel().SetFilter(bson.D{{"name", "Cafe Zucchini"}}).
SetUpdate(bson.D{{"$set", bson.D{{"name", "Zucchini Land"}}}}),
}
// 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)

완전히 실행 가능한 예제 보기

전체 예시를 실행한 후 restaurants 컬렉션에서 다음 문서를 찾을 수 있습니다.

{
"_id": ObjectId("..."),
"name": "Zucchini Land",
"cuisine": "French"
}

문서를 찾는 방법에 대한 예는 문서 찾기를 참조하세요.

컬렉션에 대한 대량 쓰기 작업 수행 및 잠재적 오류 처리에 대해 자세히 알아보려면 대량 작업을 참조하세요.

← 여러 문서 삭제