GOLANG & MongoDB

GO: Connect to MongoDB using Go

Nishee Jaiswal
4 min readJul 3, 2021

Almost every application requires a connection to a database to perform some CRUD operations. Here, our Go project will only connect to Mongo Database and create a database client.

Prerequisites

  • You will need MongoDB installed on your development machine along with the Go installer.

The operating system which we will be working on is Linux and all the directory structure and folder path descriptions will be based on Ubuntu 18.04 which is a Linux distribution. This environment setup will be similar for other versions of Ubuntu as well.

Go Project

The project which we will create inside the Go workspace will be gomongo.

nishee@ubuntu:~$ pwd 
/home/nishee
nishee@ubuntu:~$ cd go/src
nishee@ubuntu:~/go/src/$ mkdir gomongo
nishee@ubuntu:~/go/src/$ cd gomongo
nishee@ubuntu:~/go/src/gomongo$ touch main.go
nishee@ubuntu:~/go/src/gomongo$ code .

You can open your gomongo project directly from Visual Studio Code instead of code . command.

Inside the gomongo project we will now create a dao package with a filename as dao.go

Now, write the below code inside your dao.go file.

package daoimport (
"context"
"fmt"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func ConnectDB() (*mongo.Client, error) { clientOptions := options.Client().ApplyURI("mongodb://localhost:27017") client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
return nil, err
}
return client, nil
}

Inside theApplyURI()function, we mention the “<MONGODB_URI>”. To know on your local system the MONGODB_URI, just run the mongo command from your terminal from any path.

nishee@ubuntu:~$ mongo
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 4.0.0
WARNING: shell and server versions do not match
Server has startup warnings:
2021-07-03T06:00:27.571+0000 I STORAGE [initandlisten]
2021-07-03T06:00:27.571+0000 I STORAGE [initandlisten] ** WARNING: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine
2021-07-03T06:00:27.571+0000 I STORAGE [initandlisten] ** See http://dochub.mongodb.org/core/prodnotes-filesystem
2021-07-03T06:00:28.437+0000 I CONTROL [initandlisten]
2021-07-03T06:00:28.437+0000 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2021-07-03T06:00:28.437+0000 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2021-07-03T06:00:28.437+0000 I CONTROL [initandlisten]
>

Now, the output will give you the MONGODB_URIi.e. connecting to: mongodb://127.0.0.1:27017. As we know localhost is equal to 127.0.0.1, so you can use any one of them.

If the mongo-driver package inside the import section shows red wiggly lines below it and throws an error, then execute the below command to install those packages on your system, so that they can be used in your current project.

nishee@ubuntu:~/go/src/gomongo$ go get go.mongodb.org/mongo-driver/mongo
nishee@ubuntu:~/go/src/gomongo$ go get go.mongodb.org/mongo-driver/mongo/options

Now, the above package is also installed in the pkg folder of your Go workspace. Whenever the same package will be called, it will look for the package object in the pkg folder and not in the src folder. And this will save time during the compilation of your Go project.

Now, write the below code inside your main.go file.

package mainimport (
"context"
"fmt"
"log"
"mongo/dao"
)
func main() {

dbClient, err := dao.ConnectDB()
if err != nil {
log.Fatal(err)
}
defer dbClient.Disconnect(context.TODO()) fmt.Println("Connected to MongoDB!")
}

Execute the below command after saving the main.go file.

nishee@ubuntu:~/go/src/gomongo$ go run main.go

Below is the output of the above go source code file on the terminal.

Connected to MongoDB!

Database and Collection in MongoDB

Now, we will create a database and collection in MongoDB using Go.
Add the below lines in your main.go file inside the main() function.

// Create a database
database := dbClient.Database("gomongo")
// Create a collection
_ = database.Collection("go")

Now, from your terminal go to mongo and check if the database and collection are created or not.

No entry of the gomongo will be seen in dbs list. Hence, we will also insert one entry into the go collection and then check your mongo CLI from the terminal.

nishee@ubuntu:~$ mongo
> show dbs
admin 0.000GB
config 0.000GB

Now, add the below lines in your main.go file inside the main() function again.

// Create a collection
collection = database.Collection("go")
// Insert one entry into the collection
_, err = collection.InsertOne(context.TODO(), bson.M{"Hello": "World!"})
if err != nil {
log.Fatal(err)
}
nishee@ubuntu:~$ mongo
> show dbs
admin 0.000GB
config 0.000GB
gomongo 0.000GB
> use gomongo
> show collections
go
> db.go.find().pretty()

{ "_id" : ObjectId("60e0a5cb8b8dbbb0f1de5d5d"), "Hello" : "World!" }

Here, gomongo is the database name and go is the collection inside the gomongo database.

You have now successfully connected to MongoDB using Go!

--

--