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

ドキュメントの挿入

このガイドでは、MongoDB コレクションにドキュメントを挿入する方法を学習できます。

MongoDB でドキュメントを検索、更新、削除する前に、それらのドキュメントを挿入する必要があります。単一のドキュメントを挿入するには InsertOne() メソッドを、複数のドキュメントを挿入するには InsertMany() または BulkWrite() メソッドを使用します。

次のセクションでは、InsertOne() と InsertMany() に焦点を当てます。BulkWrite() メソッドの使用方法については、一括操作ガイドを参照してください。

MongoDB では、各ドキュメントにユニークな _id フィールドが含まれている必要があります。

このフィールドを管理するための 2 つのオプションは次のとおりです。

  • このフィールドを自分で管理し、使用する各値が一意であることを確認します。

  • ドライバーがユニークな ObjectId 値を自動的に生成できるようにします。ドライバーは、_id を明示的に指定していないドキュメントに対してユニークな ObjectId 値を生成します。

一意性について強力な保証を提供しない限り、MongoDB ではドライバーに _id 値を自動的に生成させることをお勧めします。

注意

重複した _id 値はユニークインデックス制約に違反するため、ドライバーは WriteError を返します。

_idフィールドの詳細については、一意なインデックス に関するサーバー マニュアル エントリを参照してください。

ドキュメント構造とルールの詳細については、ドキュメント に関するサーバー マニュアル エントリを参照してください。

単一のドキュメントをコレクションに挿入するには、InsertOne() メソッドを使用します。

挿入に成功すると、メソッドは新しいドキュメントの _id を含む InsertOneResult インスタンスを返します。

この例では、 books コレクション内のドキュメントのモデルとして次の Book 構造体を使用します。

type Book struct { Title string Author string}

次の例では、InsertOne() メソッドを使用してドキュメントを作成し、books コレクションに挿入します。

coll := client.Database("db").Collection("books")doc := Book{Title: "Atonement", Author: "Ian McEwan"} result, err := coll.InsertOne(context.TODO(), doc) fmt.Printf("Inserted document with _id: %v\n", result.InsertedID)

オプションの InsertOneOptions 構造体を構築して渡すことで、InsertOne() の動作を変更できます。InsertOneOptions で設定できるオプションは次のとおりです。

オプション
説明

BypassDocumentValidation

true の場合、書込み (write) 時にドキュメント レベルの検証をオプトアウトできます。

デフォルト: false

次のように InsertOneOptions を構築します。

opts := options.InsertOne().SetBypassDocumentValidation(true)

注意

セットアップ例

この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoClient の作成」を参照してください。この例では、Atlas サンプル データセットに含まれる sample_restaurants データベースの restaurants コレクションも使用します。「Atlas スタートガイド」の手順に従って、MongoDB Atlas の無料クラスターのデータベースにロードできます。

次の例では、新しいドキュメントを restaurantsコレクションに挿入します。対応するコードを表示するには、Struct タブまたは bson.Dタブを選択します。

次のコードでは、 構造体を使用して新しいドキュメントをrestaurantsコレクションに挿入します。

// Inserts a single document describing a restaurant by using the Go driverpackage main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options") // Defines the structure of a restaurant documenttype 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/ja-jp/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) } }() // Inserts a sample document describing a restaurant into the collection coll := client.Database("sample_restaurants").Collection("restaurants") newRestaurant := Restaurant{Name: "8282", Cuisine: "Korean"} result, err := coll.InsertOne(context.TODO(), newRestaurant) if err != nil { panic(err) } // Prints the ID of the inserted document fmt.Printf("Document inserted with ID: %s\n", result.InsertedID) // When you run this file for the first time, it should print output similar // to the following: // Document inserted with ID: ObjectID("...") }

複数のドキュメントをコレクションに挿入するには、InsertMany() メソッドを使用します。

挿入に成功すると、InsertMany() メソッドは挿入されたドキュメントの _id フィールドを含む InsertManyResult インスタンスを返します。

次の例では、InsertMany() メソッドを使用して複数のドキュメントを作成し、books コレクションに挿入します。

coll := client.Database("myDB").Collection("favorite_books")docs := []any{ Book{Title: "Cat's Cradle", Author: "Kurt Vonnegut Jr."}, Book{Title: "In Memory of Memory", Author: "Maria Stepanova"}, Book{Title: "Pride and Prejudice", Author: "Jane Austen"},} result, err := coll.InsertMany(context.TODO(), docs)fmt.Printf("Documents inserted: %v\n", len(result.InsertedIDs)) for _, id := range result.InsertedIDs { fmt.Printf("Inserted document with _id: %v\n", id)}

上記のコードを実行すると、出力は次のようになります。

Documents inserted: 3Inserted document with _id: ObjectID("...")Inserted document with _id: ObjectID("...")Inserted document with _id: ObjectID("...")

オプションの InsertManyOptions 構造体を構築して渡すことで、InsertMany() の動作を変更できます。InsertManyOptions で設定できるオプションは次のとおりです。

オプション
説明

BypassDocumentValidation

true の場合、書込み (write) 時にドキュメント レベルの検証をオプトアウトできます。

デフォルト: false

Ordered

true の場合、ドライバーは指定された順序でドキュメントをサーバーに送信します。エラーが発生した場合、ドライバーとサーバーは残りの挿入操作をすべて終了します。学ぶには、順序付きの動作を参照してください。

デフォルト: false

次のように InsertManyOptions を構築します。

opts := options.InsertMany().SetBypassDocumentValidation(true).SetOrdered(false)

たとえば、次のドキュメントを挿入するとします。

{ "_id": 1, "title": "Where the Wild Things Are" }{ "_id": 2, "title": "The Very Hungry Caterpillar" }{ "_id": 1, "title": "Blueberries for Sal" }{ "_id": 3, "title": "Goodnight Moon" }

これらのドキュメントをデフォルトの InsertManyOptions で挿入しようとすると、_id 値が繰り返されているために 3 番目のドキュメントで BulkWriteException が発生しますが、エラーが発生したドキュメントの前のドキュメントはコレクションに挿入されます。

注意

BulkWriteException が発生した場合でも、ドキュメントの挿入に成功したという確認を受け取ることができます。

type Book struct { ID int `bson:"_id"` Title string} ... docs := []any{ Book{ID: 1, Title: "Where the Wild Things Are"}, Book{ID: 2, Title: "The Very Hungry Caterpillar"}, Book{ID: 1, Title: "Blueberries for Sal"}, Book{ID: 3, Title: "Goodnight Moon"},} result, err := coll.InsertMany(context.TODO(), docs)if err != nil { fmt.Printf("A bulk write error occurred, but %v documents were still inserted.\n", len(result.InsertedIDs))} for _, id := range result.InsertedIDs { fmt.Printf("Inserted document with _id: %v\n", id)}

上記のコードを実行すると、コレクションには次のドキュメントが含まれます。

{ "_id": 1, "title": "Where the Wild Things Are" }{ "_id": 2, "title": "The Very Hungry Caterpillar" }

注意

セットアップ例

この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoClient の作成」を参照してください。この例では、Atlas サンプル データセットに含まれる sample_restaurants データベースの restaurants コレクションも使用します。「Atlas スタートガイド」の手順に従って、MongoDB Atlas の無料クラスターのデータベースにロードできます。

次の例では、複数の新しいドキュメントを restaurantsコレクションに挿入しています。対応するコードを表示するには、Struct タブまたは bson.Dタブを選択します。

次のコードでは、 構造体を使用して複数の新しいドキュメントを restaurantsコレクションに挿入します。

// Inserts sample documents describing restaurants by using the Go driverpackage main import ( "context" "fmt" "log" "os" "github.com/joho/godotenv" "go.mongodb.org/mongo-driver/v2/mongo" "go.mongodb.org/mongo-driver/v2/mongo/options") // Defines the structure of a restaurant documenttype 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/ja-jp/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 two sample documents describing restaurants newRestaurants := []any{ Restaurant{Name: "Rule of Thirds", Cuisine: "Japanese"}, Restaurant{Name: "Madame Vo", Cuisine: "Vietnamese"}, } // Inserts sample documents into the collection result, err := coll.InsertMany(context.TODO(), newRestaurants) if err != nil { panic(err) } // Prints the IDs of the inserted documents fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs)) for _, id := range result.InsertedIDs { fmt.Printf("\t%s\n", id) } // When you run this file for the first time, it should print output similar // to the following: // 2 documents inserted with IDs: // ObjectID("...") // ObjectID("...")}

上記の操作の実行方法の詳細については、次のガイドを参照してください。

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。