Monday, 19 October 2020

go web app 4 mongodb 1

mongodb compass displays several database on mongodb cloud cluster
 
//cmd - install driver
go get go.mongodb.org/mongo-driver/mongo

//cmd - connect to database
C:\Users\bob\golang3>go run main.go
[sample_airbnb sample_analytics sample_geospatial sample_mflix sample_restaurants sample_supplies sample_training sample_weatherdata admin local]

//main.go
package main

import (
"context"
"fmt"
"log"
"time"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)

func main() {
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://bob:password@cluster0.yvyo2.mongodb.net/test?retryWrites=true&w=majority"))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
databases, err := client.ListDatabaseNames(ctx, bson.M{})
err = client.Ping(ctx, readpref.Primary())
if err != nil {
log.Fatal(err)
}
fmt.Print(databases)
}

No comments:

Post a Comment