diff --git a/source/archive-reference-files/usage-examples/struct-tagging.txt b/source/archive-reference-files/usage-examples/struct-tagging.txt index 8e6aca07..6ed7b149 100644 --- a/source/archive-reference-files/usage-examples/struct-tagging.txt +++ b/source/archive-reference-files/usage-examples/struct-tagging.txt @@ -19,7 +19,7 @@ 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: -.. literalinclude:: /includes/usage-examples/code-snippets/struct-tag.go +.. literalinclude:: /includes/usage-examples/code-snippets/structTag.go :start-after: begin struct :end-before: end struct :language: go @@ -32,13 +32,13 @@ struct field as ``word_count``: .. include:: /includes/usage-examples/run-example-tip.rst -.. literalinclude:: /includes/usage-examples/code-snippets/struct-tag.go +.. literalinclude:: /includes/usage-examples/code-snippets/structTag.go :start-after: begin create and insert :end-before: end create and insert :language: go :dedent: -View a `fully runnable example. <{+example+}/struct-tag.go>`__ +View a `fully runnable example. <{+example+}/structTag.go>`__ Expected Result --------------- diff --git a/source/data-formats/struct-tagging.txt b/source/data-formats/struct-tagging.txt index 99b08837..05b08699 100644 --- a/source/data-formats/struct-tagging.txt +++ b/source/data-formats/struct-tagging.txt @@ -10,50 +10,59 @@ Use Struct Tags You can specify the way that the Go Driver converts Go structs to :manual:`BSON ` by using struct tags. -Example -------- -.. TODO: Add the Usage Examples intro include once it is merged - -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: - -.. literalinclude:: /includes/usage-examples/code-snippets/struct-tag.go - :start-after: begin struct - :end-before: end struct - :language: go - :dedent: +Example: Full File +------------------ + +.. include:: /includes/usage-examples/example-intro.rst + +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 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``: +The following code shows the ``Restaurant`` struct used in the example: -.. literalinclude:: /includes/usage-examples/code-snippets/struct-tag.go - :start-after: begin create and insert - :end-before: end create and insert +.. literalinclude:: /includes/usage-examples/code-snippets/structTagStruct.go :language: go - :dedent: -View a `fully runnable example. <{+example+}/struct-tag.go>`__ +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: + +.. io-code-block:: + :copyable: true + + .. input:: /includes/usage-examples/code-snippets/structTag.go + :language: go + :dedent: + + .. output:: + :language: none + :visible: false + + Document inserted with ID: ObjectID("...") Expected Result --------------- After you run the full example, you can find the following document -in the ``posts`` collection: +in the ``restaurants`` collection: .. code-block:: json :copyable: false { "_id" : ObjectId("..."), - "title" : "Annuals vs. Perennials?", - "author" : "Sam Lee", - "word_count" : 682, - "lastupdated": ..., - "tags" : ["seasons", "gardening", "flower"] + "name" : "Amazing Pizza", + "restaurant_id" : "123456789", + "cuisine" : "American } For an example on how to find a document, see the :ref:`golang-find-one` guide. diff --git a/source/includes/usage-examples/code-snippets/struct-tag.go b/source/includes/usage-examples/code-snippets/struct-tag.go deleted file mode 100644 index b5d55dd1..00000000 --- a/source/includes/usage-examples/code-snippets/struct-tag.go +++ /dev/null @@ -1,87 +0,0 @@ -// Specifies struct tags on a struct by using the Go driver -package main - -import ( - "context" - "encoding/json" - "fmt" - "log" - "os" - "time" - - "github.com/joho/godotenv" - "go.mongodb.org/mongo-driver/v2/bson" - "go.mongodb.org/mongo-driver/v2/mongo" - "go.mongodb.org/mongo-driver/v2/mongo/options" -) - -// Specifies a different name for the "WordCount" field when marshalling -// begin struct -type BlogPost struct { - Title string - Author string - WordCount int `bson:"word_count"` - LastUpdated time.Time - Tags []string -} - -// end struct - -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/connect/mongoclient/#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) - } - }() - - // begin create and insert - 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) - } - // end create and insert - - filter := bson.D{{"author", "Sam Lee"}} - - // Retrieves the inserted document and prints it as bson.M to see the - // alternate field name for "WordCount" - var result bson.M - err = coll.FindOne(context.TODO(), filter).Decode(&result) - if err != nil { - if err == mongo.ErrNoDocuments { - return - } - panic(err) - } - - output, err := json.MarshalIndent(result, "", " ") - if err != nil { - panic(err) - } - fmt.Printf("%s\n", output) -} diff --git a/source/includes/usage-examples/code-snippets/structTag.go b/source/includes/usage-examples/code-snippets/structTag.go new file mode 100644 index 00000000..2ecbf876 --- /dev/null +++ b/source/includes/usage-examples/code-snippets/structTag.go @@ -0,0 +1,68 @@ +// 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("...") +} diff --git a/source/includes/usage-examples/code-snippets/structTagStruct.go b/source/includes/usage-examples/code-snippets/structTagStruct.go new file mode 100644 index 00000000..8e27582a --- /dev/null +++ b/source/includes/usage-examples/code-snippets/structTagStruct.go @@ -0,0 +1,8 @@ +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"` +} \ No newline at end of file