Use Struct Tags

For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

Use Struct Tags

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 [Create a MongoClient](https://www.mongodb.com/docs/drivers/go/current/connect/mongoclient.md#std-label-golang-mongoclient. 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 a free cluster on MongoDB Atlas by following the steps in [Get Started with Atlas.](https://www.mongodb.com/docs/get-started.md#std-label-unified-get-started

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 name restaurant_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("...")
}

Output:

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](https://www.mongodb.com/docs/drivers/go/current/crud/query/retrieve.md#std-label-golang-find-one guide.

Additional Information

To learn more about using struct tags, converting to/from BSON, and handling potential errors, see the [Work with BSON](https://www.mongodb.com/docs/drivers/go/current/data-formats/bson.md#std-label-golang-bson guide.

API Documentation

  • [Structs and Struct Tags](https://pkg.go.dev/go.mongodb.org/mongo-driver/v2@v2.9.2/bson#hdr-Structs

  • [InsertOne()](https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo#Collection.InsertOne

  • [FindOne()](https://pkg.go.dev/go.mongodb.org/mongo-driver/v2/mongo#Collection.FindOne