第6章: Golang MongoDB におけるドキュメント挿入

ドキュメントの挿入

result, err := collection.InsertOne(
	context.Background(),  // コンテキストパラメータ
	bson.D{   // bson.D を使用して JSON ドキュメントを定義
		{"item", "canvas"},
		{"qty", 100},
		{"tags", bson.A{"cotton"}},
		{"size", bson.D{
			{"h", 28},
			{"w", 35.5},
			{"uom", "cm"},
		}},
	})
	
// ドキュメントのために生成されたユニークなIDを取得
id := result.InsertedID

ヒント: Golang MongoDB のデータ表現に慣れていない場合、こちらの "Golang MongoDB データモデル" セクションを参照してください。

次のJSONドキュメントを挿入するのと同等です:

{
	"item": "canvas",
	"qty": 100,
	"tags": ["cotton"],
	"size": {
		"h": 28,
		"w": 35.5,
		"uom": "cm"
	}
}

新しく挿入されたドキュメントのクエリ

cursor, err := collection.Find(
	context.Background(),
	bson.D{{"item", "canvas"}},  // 同値式: {"item": "canvas"}
)

バルク挿入

result, err := collection.InsertMany(
	context.Background(),
	[]interface{}{   // ドキュメントデータの配列を渡し、3つのドキュメントデータを挿入
		bson.D{ // ドキュメントデータ1
			{"item", "journal"},
			{"qty", int32(25)},
			{"tags", bson.A{"blank", "red"}},
			{"size", bson.D{
				{"h", 14},
				{"w", 21},
				{"uom", "cm"},
			}},
		},
		bson.D{ // ドキュメントデータ2
			{"item", "mat"},
			{"qty", int32(25)},
			{"tags", bson.A{"gray"}},
			{"size", bson.D{
				{"h", 27.9},
				{"w", 35.5},
				{"uom", "cm"},
			}},
		},
		bson.D{ // ドキュメントデータ3
			{"item", "mousepad"},
			{"qty", 25},
			{"tags", bson.A{"gel", "blue"}},
			{"size", bson.D{
				{"h", 19},
				{"w", 22.85},
				{"uom", "cm"},
			}},
		},
	})

すべてのドキュメントのクエリ

cursor, err := collection.Find(
	context.Background(),
	bson.D{}, // 空のクエリ条件を渡す
)