장 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{}{ // 문서 데이터 배열을 전달하여 세 개의 문서 데이터 삽입
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{}, // 빈 쿼리 조건 전달
)