Docs Menu
Docs Home
/ / /
Go 드라이버
/ /

여러 문서를 삽입합니다.

InsertMany() 방법을 사용하면 컬렉션에서 여러 문서를 삽입할 수 있습니다.

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

이 예제에서는 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")
// 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)
}

실행 가능한 예시 보기

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

{ "_id": ObjectID("..."), "name": "Rule of Thirds", "cuisine": "Japanese"},
{ "_id": ObjectID("..."), "name": "Madame Vo", "cuisine": "Vietnamese"}

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

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

InsertMany()

돌아가기

문서 삽입