Go ドライバーが Go 構造体をBSONに変換する方法を指定するには、構造体タグを使用します。
例: 完全なファイル
注意
セットアップ例
この例では、接続 URI を使用して MongoDB インスタンスに接続します。MongoDB インスタンスへの接続の詳細については、「MongoClient の作成」を参照してください。この例では、Atlas サンプル データセットに含まれる sample_restaurants データベースの restaurants コレクションも使用します。「Atlas スタートガイド」の手順に従って、MongoDB Atlas の無料クラスターのデータベースにロードできます。
この例では、次の構造体タグを使用して Restaurant 型の構造体を宣言します。
RestaurantIdフィールドをBSONフィールド名restaurant_idにマッピングする構造体タグ。デフォルトでは 、ドライバーは他のフィールドを構造フィールド名の小文字としてマーシャリングします。omitempty構造体タグが空のままの場合、挿入されたドキュメントの対応フィールドが省略されます。
次のコードは、例で使用されている 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 driverpackage 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 omitemptytype 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/ja-jp/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("...")}期待される結果
完全な例を実行すると、 restaurantsコレクションに次のドキュメントが見つかります。
{ "_id" : ObjectId("..."), "name" : "Amazing Pizza", "restaurant_id" : "123456789", "cuisine" : "American}ドキュメントを検索する方法の例については、ドキュメントの検索ガイドを参照してください。
詳細情報
構造体タグの使用、 BSONとの間の変換、および潜在的なエラーの処理の詳細については、 BSONとの連携ガイドを参照してください。