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

構造タグを使用する

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 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/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("...")
}
Document inserted with ID: ObjectID("...")

完全な例を実行すると、 restaurantsコレクションに次のドキュメントが見つかります。

{
"_id" : ObjectId("..."),
"name" : "Amazing Pizza",
"restaurant_id" : "123456789",
"cuisine" : "American
}

ドキュメントを検索する方法の例については、ドキュメントの検索ガイドを参照してください。

構造体タグの使用、 BSONとの間の変換、および潜在的なエラーの処理の詳細については、 BSONとの連携ガイドを参照してください。

戻る

Data Formats