Connect to MongoDB in Go
Hi, today I show you how to connect to MongoDB on Golang and create first collection!
In this article we will be using .env, I have an article about .evn , click here if you don’t know how to use .env in go.
MongoDB is a non-relational document database(NoSQL) that provides support for JSON-like storage. The MongoDB database has a flexible data model that enables you to store unstructured data, and it provides full indexing support, and replication with rich and intuitive APIs.
Go, also called Golang or Go language, is an open source programming language that Google developed. Software developers use Go in an array of operating systems and frameworks to develop web applications, cloud and networking services, and other types of software.
Step 1: Init go mod and install mongoDB driver
Init our project :
go mod init connect-to-mongodb
Install mongoDB driver and dotenv:
go get go.mongodb.org/mongo-driver/mongo
go get github.com/joho/godotenv
Step 2: Find your MONGO_URI in .env
Here i show how to get MONGO_URI in .env:
func Connect() *mongo.Collection {
// Find .evn
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file: %s", err)
}
// Get value from .env
MONGO_URI := os.Getenv("MONGO_URI")
}
Step 3: Connect to the database.
Here i show how to simple connect to the database
func Connect() *mongo.Collection {
// Find .evn
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file: %s", err)
}
// Get value from .env
MONGO_URI := os.Getenv("MONGO_URI")
// Connect to the database.
clientOptions := options.Client().ApplyURI(MONGO_URI)
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal(err)
}
}
Step 4: Check the connection.
Here we check the connection to our DB
func Connect() {
// Find .evn
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file: %s", err)
}
// Get value from .env
MONGO_URI := os.Getenv("MONGO_URI")
// Connect to the database.
clientOptions := options.Client().ApplyURI(MONGO_URI)
client, err := mongo.Connect(context.Background(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Check the connection.
err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal(err)
}else{
fmt.Println("Connected to mongoDB!!!")
}
}
Step 5: Create first collection
Here i show how to create a first collection
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main(){
Connect();
}
func Connect() *mongo.Collection {
// Find .evn
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file: %s", err)
}
// Get value from .env
MONGO_URI := os.Getenv("MONGO_URI")
// Connect to the database.
clientOption := options.Client().ApplyURI(MONGO_URI)
client, err := mongo.Connect(context.Background(), clientOption)
if err != nil {
log.Fatal(err)
}
// Check the connection.
err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
// Create collection
collection := client.Database("testdb").Collection("test")
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to db")
return collection
}
The full code
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/joho/godotenv"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main(){
Connect();
}
func Connect() *mongo.Collection {
// Find .evn
err := godotenv.Load(".env")
if err != nil {
log.Fatalf("Error loading .env file: %s", err)
}
// Get value from .env
MONGO_URI := os.Getenv("MONGO_URI")
// Connect to the database.
clientOption := options.Client().ApplyURI(MONGO_URI)
client, err := mongo.Connect(context.Background(), clientOption)
if err != nil {
log.Fatal(err)
}
// Check the connection.
err = client.Ping(context.Background(), nil)
if err != nil {
log.Fatal(err)
}
// Create collection
collection := client.Database("testdb").Collection("test")
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to db")
return collection
}
Output:
danilbolsakov@Danils-MacBook-Pro mongodb % go run .
Connected to db
Thank you for the read that article!
You can buy me a coffee!