You can specify the way that the Go Driver converts Go structs to BSON by using struct tags.
Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Create a MongoClient guide. This example
also uses the restaurants
collection in the sample_restaurants
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas
by following the Get Started with Atlas Guide.
This example declares a struct of type Restaurant
with the
following struct tags:
A struct tag that maps the
RestaurantId
field to the BSON field namerestaurant_id
. By default, the driver marshals the other fields as the lowercase of the struct field name.The
omitempty
struct tag omits the corresponding field from the inserted document when left empty.
The following code shows the Restaurant
struct used in the example:
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"` }
The following example creates a Restaurant
instance and inserts it
into the restaurants
collection. During the insert operation, the driver
interprets the struct tags to marshal the RestaurantId
struct field as restaurant_id
and omits fields that are left empty in the
sample document:
// 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/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("...")
Expected Result
After you run the full example, you can find the following document
in the restaurants
collection:
{ "_id" : ObjectId("..."), "name" : "Amazing Pizza", "restaurant_id" : "123456789", "cuisine" : "American }
For an example on how to find a document, see the Find Documents guide.
Additional Information
To learn more about using struct tags, converting to/from BSON, and handling potential errors, see the Work with BSON guide.