고(Go) 드라이버가 구조체 태그를 사용하여 고(Go) 구조체를 BSON으로 변환하는 방식을 지정할 수 있습니다.
예제: 전체 파일
참고
설정 예시
이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습 MongoClient 만들기 가이드 참조하세요. 이 예시 Atlas 샘플 데이터 세트에 포함된 sample_restaurants
데이터베이스의 restaurants
컬렉션도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.
이 예시 다음 구조체 태그를 사용하여 Restaurant
유형의 구조체를 선언합니다.
RestaurantId
필드 BSON 필드 이름restaurant_id
에 매핑하는 구조체 태그를 지정하다 입니다. 기본값 으로 운전자 다른 필드를 구조체 필드 이름의 소문자로 마셜링합니다.omitempty
struct 태그 는 비어 있을 때 삽입된 문서에서 해당 필드를 생략합니다.
다음 코드는 예시 에 사용된 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"` }
다음 예시 Restaurant
인스턴스 만들어 restaurants
컬렉션 에 삽입합니다. 삽입 작업 중에 운전자 구조체 태그를 해석하여 RestaurantId
구조체 필드 restaurant_id
(으)로 마셜링하고 샘플 문서 에서 비어 있는 필드를 생략합니다.
// Specifies struct tags on a struct 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" ) // Specifies a different name for RestaurantID // and marks certain fields as omitempty 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/usage-examples/#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 a Restaurant document newRestaurant := Restaurant{ Name: "Amazing Pizza", RestaurantId: "123456789", Cuisine: "American", } // Inserts the sample document describing a restaurant into the collection 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, it should print: // Document inserted with ID: ObjectID("...") }
Document inserted with ID: ObjectID("...")
예상 결과
전체 예시를 실행한 후 restaurants
컬렉션에서 다음 문서를 찾을 수 있습니다.
{ "_id" : ObjectId("..."), "name" : "Amazing Pizza", "restaurant_id" : "123456789", "cuisine" : "American }
문서 찾는 방법에 대한 예시는 문서 찾기 가이드를 참조하세요.
추가 정보
구조체 태그 사용, BSON 으로의 변환 및 잠재적 오류 처리에 대해 자세히 학습하려면 BSON 작업 가이드 를 참조하세요.