Docs Menu
Docs Home
/ / /
Go Driver
/ / /

ドキュメントの挿入

項目一覧

  • Overview
  • _id フィールド
  • ドキュメントの挿入
  • InsertOne 動作を変更する
  • 複数のドキュメントの挿入
  • InsertMany 動作を変更する
  • Ordered 動作
  • 詳細情報
  • API ドキュメント

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

MongoDB でドキュメントを検索、更新、削除する前に、それらのドキュメントを挿入する必要があります。InsertOne() メソッドを使用して 1 つのドキュメントを挿入することも、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
If true, allows the write to opt-out of document level validation.
Default: false

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

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

複数のドキュメントをコレクションに挿入するには、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("...")

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

オプション
説明
BypassDocumentValidation
If true, allows the write to opt-out of document level validation.
Default: false
Ordered
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)
}

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

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

挿入操作の実行可能な例については、次の使用例を参照してください。

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

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

戻る

書込み操作