AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。

一括操作の実行

BulkWrite()メソッドを使用して、コレクションに対して一括書き込み操作を実行できます。

Tip

この例を実行する方法については、「使用例」をお読みください。

この例では、 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 構造体タグが空のままの場合、挿入されたドキュメントの対応フィールドが省略されます。

次の例えでは、 restaurantsコレクションに対して次の操作を順番に実行します。

  • nameが「Cafe analyzer」であるドキュメントに一致し、それが新しいドキュメントに置き換えられます

  • nameが "Cafe協定世界" であるドキュメントに一致し、 の値を "Zuc内メント" に更新します。

coll := client.Database("sample_restaurants").Collection("restaurants") // Creates write models that specify replace and update operationsmodels := []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 orderedopts := options.BulkWrite().SetOrdered(true) // Runs a bulk write operation for the specified write operationsresults, err := coll.BulkWrite(context.TODO(), models, opts)

実行可能な例を表示

完全な例を実行すると、 restaurantsコレクションに次のドキュメントが見つかります。

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

ドキュメントの検索方法の例については、「ドキュメントを検索する」を参照してください。

コレクションに対して一括書き込み操作の実行と潜在的なエラーの処理の詳細については、「一括操作 」を参照してください。

このページを評価