Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Go 드라이버
/

문서 삽입

이 가이드에서는 MongoDB 컬렉션에 문서를 삽입하는 방법을 배울 수 있습니다.

MongoDB에서 문서를 찾고, 업데이트하고, 삭제하려면 먼저 해당 문서를 삽입해야 합니다. InsertOne() 메서드를 사용하여 하나의 문서를 삽입하거나 InsertMany() 또는 BulkWrite() 메서드를 사용하여 여러 개의 문서를 삽입할 수 있습니다.

다음 섹션에서는 InsertOne()InsertMany()에 중점을 둡니다. BulkWrite() 메서드 사용 방법을 알아보려면 대량 작업 가이드를 참조하세요.

MongoDB에서는 각 문서에 고유한 _id 필드가 포함되어야 합니다 .

이 필드를 관리하기 위한 옵션 두 가지는 다음과 같습니다.

  • 이 필드를 직접 관리하여 사용하는 각 값이 고유한지 확인하세요.

  • 드라이버가 고유한 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)
Inserted document with _id: ObjectID("...")

선택적 InsertOneOptions 구조체를 구성하고 전달하여 InsertOne() 의 동작을 수정할 수 있습니다. InsertOneOptions로 설정할 수 있는 옵션은 다음과 같습니다:

옵션
설명

BypassDocumentValidation

If true, allows the write to opt-out of document level validation.
Default: false

다음과 같이 InsertOneOptions을 생성합니다:

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

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants 데이터베이스restaurants 컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 예시 restaurants 컬렉션 에 새 문서 삽입합니다. Struct 또는 bson.D 탭 선택하여 해당 코드를 확인합니다.

다음 코드에서는 구조체를 사용하여 restaurants 컬렉션 에 새 문서 삽입합니다.

// Inserts a single document describing a restaurant by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Defines the structure of a restaurant document
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"`
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
// Inserts a sample document describing a restaurant into the 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)
}
// Prints the ID of the inserted document
fmt.Printf("Document inserted with ID: %s\n", result.InsertedID)
// When you run this file for the first time, it should print output similar
// to the following:
// Document inserted with ID: ObjectID("...")
}
Document inserted with ID: ObjectID("...")

다음 코드에서는 bson.D 유형을 사용하여 restaurants 컬렉션 에 새 문서 삽입합니다.

// Inserts a single document describing a restaurant by using the Go driver with bson.D
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
// Inserts a sample document describing a restaurant into the collection using bson.D
coll := client.Database("sample_restaurants").Collection("restaurants")
newRestaurant := bson.D{
bson.E{Key: "name", Value: "8282"},
bson.E{Key: "cuisine", Value: "Korean"},
}
result, err := coll.InsertOne(context.TODO(), newRestaurant)
if err != nil {
panic(err)
}
// Prints the ID of the inserted document
fmt.Printf("Document inserted with ID: %s\n", result.InsertedID)
// When you run this file for the first time, it should print output similar
// to the following:
// Document inserted with ID: ObjectID("...")
}
Document inserted with ID: ObjectID("...")

여러 문서를 컬렉션에 삽입하려면 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 값으로 인해 세 번째 문서에서 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)
}
A bulk write error occurred, but 2 documents were still inserted.
Inserted document with _id: 1
Inserted document with _id: 2

앞의 코드를 실행하면 컬렉션에 다음과 같은 문서가 포함됩니다:

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

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoClient 만들기 가이드를 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants 데이터베이스restaurants 컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 예시 restaurants 컬렉션 에 여러 개의 새 문서를 삽입합니다. Struct 또는 bson.D 탭 선택하여 해당 코드를 확인합니다.

다음 코드에서는 구조체를 사용하여 restaurants 컬렉션 에 여러 개의 새 문서를 삽입합니다.

// Inserts sample documents describing restaurants by using the Go driver
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
// Defines the structure of a restaurant document
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"`
}
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
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)
}
// Prints the IDs of the inserted documents
fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs))
for _, id := range result.InsertedIDs {
fmt.Printf("\t%s\n", id)
}
// When you run this file for the first time, it should print output similar
// to the following:
// 2 documents inserted with IDs:
// ObjectID("...")
// ObjectID("...")
}
2 documents inserted with IDs:
ObjectID("...")
ObjectID("...")

다음 코드는 bson.D 유형을 사용하여 restaurants 컬렉션 에 여러 개의 새 문서를 삽입합니다.

// Inserts sample documents describing restaurants by using the Go driver with bson.D
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
func main() {
if err := godotenv.Load(); err != nil {
log.Println("No .env file found")
}
var uri string
if uri = os.Getenv("MONGODB_URI"); uri == "" {
log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ko-kr/docs/drivers/go/current/connect/mongoclient/#environment-variable")
}
client, err := mongo.Connect(options.Client().ApplyURI(uri))
if err != nil {
panic(err)
}
defer func() {
if err = client.Disconnect(context.TODO()); err != nil {
panic(err)
}
}()
coll := client.Database("sample_restaurants").Collection("restaurants")
// Creates two sample documents describing restaurants using bson.D
newRestaurants := []interface{}{
bson.D{
bson.E{Key: "name", Value: "Rule of Thirds"},
bson.E{Key: "cuisine", Value: "Japanese"},
},
bson.D{
bson.E{Key: "name", Value: "Madame Vo"},
bson.E{Key: "cuisine", Value: "Vietnamese"},
},
}
// Inserts sample documents into the collection
result, err := coll.InsertMany(context.TODO(), newRestaurants)
if err != nil {
panic(err)
}
// Prints the IDs of the inserted documents
fmt.Printf("%d documents inserted with IDs:\n", len(result.InsertedIDs))
for _, id := range result.InsertedIDs {
fmt.Printf("\t%s\n", id)
}
// When you run this file for the first time, it should print output similar
// to the following:
// 2 documents inserted with IDs:
// ObjectID("...")
// ObjectID("...")
}
2 documents inserted with IDs:
ObjectID("...")
ObjectID("...")

언급된 작업을 수행하는 방법에 대해 자세히 알아보려면 다음 가이드를 참조하세요:

이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

CRUD 작업

이 페이지의 내용