How to do it...

These steps cover writing and running your application:

  1. From your Terminal or console application, create a new directory called ~/projects/go-programming-cookbook/chapter6/mongodb and navigate to this directory.
  2. Run the following command:
$ go mod init github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter6/mongodb

You should see a file called go.mod that containing the following:

module github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter6/mongodb    
  1. Copy tests from ~/projects/go-programming-cookbook-original/chapter6/mongodb, or use this as an exercise to write some code of your own!
  1. Create a file called config.go with the following content:
package mongodb

import (
"context"
"time"

"github.com/mongodb/mongo-go-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)

// Setup initializes a mongo client
func Setup(ctx context.Context, address string) (*mongo.Client, error) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
// cancel will be called when setup exits
defer cancel()

client, err := mongo.NewClient(options.Client().ApplyURI(address))
if err != nil {
return nil, err
}

if err := client.Connect(ctx); err != nil {
return nil, err
}
return client, nil
}
  1. Create a file called exec.go with the following content:
package mongodb

import (
"context"
"fmt"

"github.com/mongodb/mongo-go-driver/bson"
)

// State is our data model
type State struct {
Name string `bson:"name"`
Population int `bson:"pop"`
}

// Exec creates then queries an Example
func Exec(address string) error {
ctx := context.Background()
db, err := Setup(ctx, address)
if err != nil {
return err
}

coll := db.Database("gocookbook").Collection("example")

vals := []interface{}{&State{"Washington", 7062000}, &State{"Oregon", 3970000}}

// we can inserts many rows at once
if _, err := coll.InsertMany(ctx, vals); err != nil {
return err
}

var s State
if err := coll.FindOne(ctx, bson.M{"name": "Washington"}).Decode(&s); err != nil {
return err
}

if err := coll.Drop(ctx); err != nil {
return err
}

fmt.Printf("State: %#v\n", s)
return nil
}
  1. Navigate to example.
  2. Create a file called main.go with the following content:
package main

import "github.com/PacktPublishing/Go-Programming-Cookbook-Second-Edition/chapter6/mongodb"

func main() {
if err := mongodb.Exec("mongodb://localhost"); err != nil {
panic(err)
}
}
  1. Run go run main.go.
  2. You could also run the following command:
$ go build
$ ./example

You should see the following output:

$ go run main.go
State: mongodb.State{Name:"Washington", Population:7062000}
  1. The go.mod file may be updated and go.sum file should now be present in the top-level recipe directory.
  1. If you copied or wrote your own tests, go up one directory and run go test. Ensure that all tests pass.