Server-Side Scripting/Document Databases/Go

routes/lesson10.go
"   return result }

func countryExists10(country string) bool { client, err := mongo.NewClient(options.Client.ApplyURI(HOST)) if err != nil { log.Fatal(err) }

ctxt, _ := context.WithTimeout(context.Background, 10 * time.Second) err = client.Connect(ctxt) if err != nil { log.Fatal(err) }   defer client.Disconnect(ctxt)

collection := client.Database(DATABASE).Collection(COLLECTION) filter := bson.D { {"country", country}, }   count, err := collection.CountDocuments(ctxt, filter) if err != nil { log.Fatal(err) }

return count == 1 }

func insertCountry10(country string, temperature string) { value, err := strconv.ParseFloat(temperature, 32) if err != nil { log.Fatal(err) }

client, err := mongo.NewClient(options.Client.ApplyURI(HOST)) if err != nil { log.Fatal(err) }

ctxt, _ := context.WithTimeout(context.Background, 10 * time.Second) err = client.Connect(ctxt) if err != nil { log.Fatal(err) }   defer client.Disconnect(ctxt)

collection := client.Database(DATABASE).Collection(COLLECTION) document := bson.D { {"country", country}, {"temperature", value}, }   _, err = collection.InsertOne(ctxt, document) if err != nil { log.Fatal(err) } }

func updateCountry10(country string, temperature string) { value, err := strconv.ParseFloat(temperature, 32) if err != nil { log.Fatal(err) }

client, err := mongo.NewClient(options.Client.ApplyURI(HOST)) if err != nil { log.Fatal(err) }

ctxt, _ := context.WithTimeout(context.Background, 10 * time.Second) err = client.Connect(ctxt) if err != nil { log.Fatal(err) }   defer client.Disconnect(ctxt)

collection := client.Database(DATABASE).Collection(COLLECTION) filter := bson.M { "country": country, }   update := bson.D{        {"$set", bson.D}, }   _, err = collection.UpdateOne(ctxt, filter, update) if err != nil { log.Fatal(err) } }

func deleteCountry10(country string) { client, err := mongo.NewClient(options.Client.ApplyURI(HOST)) if err != nil { log.Fatal(err) }

ctxt, _ := context.WithTimeout(context.Background, 10 * time.Second) err = client.Connect(ctxt) if err != nil { log.Fatal(err) }   defer client.Disconnect(ctxt)

collection := client.Database(DATABASE).Collection(COLLECTION) filter := bson.M { "country": country, }   _, err = collection.DeleteOne(ctxt, filter) if err != nil { log.Fatal(err) } }

Try It
See ../../Routes and Templates/Go to create a test environment.