문서 메뉴
문서 홈
/ / /
Go 드라이버
/ /

문서 삽입

InsertOne() 메서드를 사용하여 collection에 문서를 삽입할 수 있습니다.

이 예제를 실행하는 방법을 알아보려면 사용 예제 를 읽어보세요.

이 예제에서는 restaurants 컬렉션의 문서에 대한 모델로 다음 Restaurant 구조체를 사용합니다:

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"`
}

omitempty struct 태그 는 비어 있을 때 삽입된 문서에서 해당 필드를 생략합니다.

다음 예에서는 restaurants 컬렉션에 새 문서를 삽입합니다.

존재하지 않는 데이터베이스 및 collection

쓰기 작업을 수행할 때 필요한 데이터베이스 및 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)
}

실행 가능한 예시 보기

전체 예시를 실행한 후 restaurants 컬렉션에서 다음의 삽입된 문서를 찾을 수 있습니다.

{
"_id": ObjectId("..."),
"name": "8282",
"cuisine": "Korean"
}

문서를 찾는 방법에 대한 예시는 문서 찾기 사용 예시를 참조하세요.

문서 삽입에 대해 자세히 알아보려면 문서 삽입하기를 참조하세요 .

InsertOne()

← 쓰기 작업