Mongo-DB with GO
This article aims at providing basic knowledge regarding the use of the mongo-DB database with your GO application.
There are certain pre-requisites before moving on:
- Mongo-DB installed and running on the default server port i.e. 27017
- Database username, password and a new db collection
For installation instructions and general information regarding creating users and collection in mongo, please visit the official mongo-DB documentation.
Getting Started
Let's create a new directory and a main.go file for us to work on.
mkdir mongo-go
cd mongo-go
touch main.go
Before starting to work on the actual code, let's install the package go.mongodb.org/mongo-driver/mongo. To do enter the following in your terminal.
go get go.mongodb.org/mongo-driver/mongo
Now, go ahead and copy the following code in to your main.go file.
package mainimport (
"context"
"fmt"
"time""go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)func main() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx…