Skip to content

Instantly share code, notes, and snippets.

@sedataktas
Last active December 24, 2020 22:06
Show Gist options
  • Select an option

  • Save sedataktas/68c49a107fa2a034411d91bef5bf1aab to your computer and use it in GitHub Desktop.

Select an option

Save sedataktas/68c49a107fa2a034411d91bef5bf1aab to your computer and use it in GitHub Desktop.
MongoDB conenction
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
)
var (
BooksCollection *mongo.Collection
AuthorsCollection *mongo.Collection
Ctx = context.TODO()
)
/*Setup opens a database connection to mongodb*/
func Setup() {
host := "127.0.0.1"
port := "27017"
connectionURI := "mongodb://" + host + ":" + port + "/"
clientOptions := options.Client().ApplyURI(connectionURI)
client, err := mongo.Connect(Ctx, clientOptions)
if err != nil {
log.Fatal(err)
}
err = client.Ping(Ctx, nil)
if err != nil {
log.Fatal(err)
}
db := client.Database("example")
BooksCollection = db.Collection("books")
AuthorsCollection = db.Collection("authors")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment