Overview
このガイドでは、MongoDB コレクションにドキュメントを挿入する方法を学習できます。
MongoDB でドキュメントを検索、更新、削除する前に、それらのドキュメントを挿入する必要があります。InsertOne()
メソッドを使用して 1 つのドキュメントを挿入することも、InsertMany()
メソッドまたは BulkWrite()
メソッドを使用して複数のドキュメントを挿入することもできます。
次のセクションでは、InsertOne()
と InsertMany()
に焦点を当てます。BulkWrite()
メソッドの使用方法については、一括操作ガイドをご覧ください。
_id フィールド
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)
Inserted document with _id: ObjectID("...")
InsertOne() の動作の変更
オプションの InsertOneOptions
構造体を構築して渡すことで、InsertOne()
の動作を変更できます。InsertOneOptions
で設定できるオプションは次のとおりです。
オプション | 説明 |
---|---|
| If true , allows the write to opt-out of document level validation.Default: 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 driver package 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 document 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"` } 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("...") }
Document inserted with ID: ObjectID("...")
次のコードでは、bson.D
タイプを使用して新しいドキュメントをrestaurants
コレクションに挿入します。
// Inserts a single document describing a restaurant by using the Go driver with bson.D 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" ) 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 using bson.D coll := client.Database("sample_restaurants").Collection("restaurants") newRestaurant := bson.D{ bson.E{Key: "name", Value: "8282"}, bson.E{Key: "cuisine", Value: "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("...") }
Document inserted with ID: ObjectID("...")
複数のドキュメントの挿入
複数のドキュメントをコレクションに挿入するには、InsertMany()
メソッドを使用します。
挿入に成功すると、InsertMany()
メソッドは挿入されたドキュメントの _id
フィールドを含む InsertManyResult
インスタンスを返します。
例
次の例では、InsertMany()
メソッドを使用して複数のドキュメントを作成し、books
コレクションに挿入します。
coll := client.Database("myDB").Collection("favorite_books") docs := []interface{}{ 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: 3 Inserted document with _id: ObjectID("...") Inserted document with _id: ObjectID("...") Inserted document with _id: ObjectID("...")
InsertMany() の動作を変更する
オプションの InsertManyOptions
構造体を構築して渡すことで、InsertMany()
の動作を変更できます。InsertManyOptions
で設定できるオプションは次のとおりです。
オプション | 説明 |
---|---|
| If true , allows the write to opt-out of document level validation.Default: false |
| If true , the driver sends documents to the server in the order provided.
If an error occurs, the driver and server end all remaining insert operations.
To learn more, see Ordered Behavior.Default: 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 := []interface{}{ 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) }
A bulk write error occurred, but 2 documents were still inserted. Inserted document with _id: 1 Inserted document with _id: 2
上記のコードを実行すると、コレクションには次のドキュメントが含まれます。
{ "_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 driver package 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 document 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"` } 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 := []interface{}{ 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("...") }
2 documents inserted with IDs: ObjectID("...") ObjectID("...")
次のコードでは、bson.D
タイプを使用して、複数の新しいドキュメントを restaurants
コレクションに挿入します。
// Inserts sample documents describing restaurants by using the Go driver with bson.D 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" ) 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 using bson.D newRestaurants := []interface{}{ bson.D{ bson.E{Key: "name", Value: "Rule of Thirds"}, bson.E{Key: "cuisine", Value: "Japanese"}, }, bson.D{ bson.E{Key: "name", Value: "Madame Vo"}, bson.E{Key: "cuisine", Value: "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("...") }
2 documents inserted with IDs: ObjectID("...") ObjectID("...")
詳細情報
上記の操作の実行方法の詳細については、次のガイドを参照してください。
API ドキュメント
このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。