Docs Menu
Docs Home
/ / /
Go Driver
/

Use Struct Tags

You can specify the way that the Go Driver converts Go structs to BSON by using struct tags.

Tip

Read the Usage Examples to learn how to run this example.

The following code declares a struct of type BlogPost. This struct contains a struct tag that maps the WordCount field to the BSON field name word_count. By default, the driver marshals the other fields as the lowercase of the struct field name:

type BlogPost struct {
Title string
Author string
WordCount int `bson:"word_count"`
LastUpdated time.Time
Tags []string
}

The following example creates a BlogPost instance and inserts it into the posts collection. During the insert operation, the driver interprets the struct tag to marshal the WordCount struct field as word_count:

Tip

Read the Usage Examples to learn how to run this example.

coll := client.Database("sample_training").Collection("posts")
post := BlogPost{
Title: "Annuals vs. Perennials?",
Author: "Sam Lee",
WordCount: 682,
LastUpdated: time.Now(),
Tags: []string{"seasons", "gardening", "flower"},
}
// Inserts a document describing a blog post into the collection
_, err = coll.InsertOne(context.TODO(), post)
if err != nil {
panic(err)
}

View a fully runnable example.

After you run the full example, you can find the following document in the posts collection:

{
"_id" : ObjectId("..."),
"title" : "Annuals vs. Perennials?",
"author" : "Sam Lee",
"word_count" : 682,
"lastupdated": ...,
"tags" : ["seasons", "gardening", "flower"]
}

For an example on how to find a document, see Find a Document.

To learn more about using struct tags, converting to/from BSON, and handling potential errors, see working with BSON.

Back

Run a Command