Skip to content
Santekno.com | Level Up Your Engineering Skills
EN
📖 0%
04 Apr 2023 · 6 min read ·Article 92 / 119
Go

How To Communication Golang with MongoDB

IH
Ihsan Arif
Writer at Santekno · Backend Engineer

Dependecy Needed

Add some dependency when we used

go
1"go.mongodb.org/mongo-driver/bson"
2"go.mongodb.org/mongo-driver/mongo"
3"go.mongodb.org/mongo-driver/mongo/options"

Create a Database Connection

create database connection function into mongoDB.

go
 1func connect() (*mongo.Database, error) {
 2	clientOptions := options.Client()
 3	clientOptions.ApplyURI("mongodb+srv://test:test@cluster0.awkve.mongodb.net/?retryWrites=true&w=majority")
 4	client, err := mongo.NewClient(clientOptions)
 5	if err != nil {
 6		return nil, err
 7	}
 8
 9	err = client.Connect(context.Background())
10	if err != nil {
11		return nil, err
12	}
13
14	return client.Database("recordings"), nil
15}

Different from the others, to make this connection we need to initialize the connection, then we create a connection to the mongodb database.

go
1clientOptions := options.Client()
2clientOptions.ApplyURI("mongodb+srv://test:test@cluster0.awkve.mongodb.net/?retryWrites=true&w=majority")

Then proceed with creating client initialization which is used so that the client ensures connection to the MongoDB database.

go
1client, err := mongo.NewClient(clientOptions)
2if err != nil {
3  return nil, err
4}

Next, we create connect so that we ensure the connection to the database.

go
1err = client.Connect(context.Background())
2if err != nil {
3  return nil, err
4}

End by choosing which database (collection) we will choose.

go
1return client.Database("recordings"), nil

Create a function to add data to an album

In the add data function, we need to call the connection first so that we can retrieve the data collection and insert the data into the database.

go
 1func insert() {
 2	db, err := connect()
 3	if err != nil {
 4		log.Fatal(err.Error())
 5	}
 6
 7	ctx := context.Background()
 8
 9	_, err = db.Collection("album").InsertOne(ctx, Album{ID: 1, Title: "Hari Yang Cerah", Artist: "Peterpan", Price: 50000})
10	if err != nil {
11		log.Fatal(err.Error())
12	}
13
14	_, err = db.Collection("album").InsertOne(ctx, Album{ID: 2, Title: "Sebuah Nama Sebuah Cerita", Artist: "Peterpan", Price: 50000})
15	if err != nil {
16		log.Fatal(err.Error())
17	}
18
19	fmt.Println("Insert success!")
20}

The command used for inserting is InsertOne where we save one data collection into the recordings database.

go
1_, err = db.Collection("album").InsertOne(ctx, Album{ID: 1, Title: "Hari Yang Cerah", Artist: "Peterpan", Price: 50000})
2if err != nil {
3  log.Fatal(err.Error())
4}

Create Displays albums

Next we will create a function to retrieve data into mongodb for with id = `. Here are the complete functions.

go
 1func find() {
 2	ctx := context.Background()
 3	db, err := connect()
 4	if err != nil {
 5		log.Fatal(err.Error())
 6	}
 7
 8	csr, err := db.Collection("album").Find(ctx, bson.M{"id": 1})
 9	if err != nil {
10		log.Fatal(err.Error())
11	}
12	defer csr.Close(ctx)
13
14	result := make([]Album, 0)
15	for csr.Next(ctx) {
16		var row Album
17		err := csr.Decode(&row)
18		if err != nil {
19			log.Fatal(err.Error())
20		}
21
22		result = append(result, row)
23	}
24
25	if len(result) > 0 {
26		fmt.Println("Title  :", result[0].Title)
27		fmt.Println("Artist :", result[0].Artist)
28		fmt.Println("Price  :", result[0].Price)
29	}
30}

When retrieving data into MongoDB we take the album collection then we use the Find function to retrieve one of the data which we are using here is ID number one.

go
1csr, err := db.Collection("album").Find(ctx, bson.M{"id": 1})
2if err != nil {
3  log.Fatal(err.Error())
4}
5defer csr.Close(ctx)

Don’t forget to close every DB connection by calling the command below.

go
1defer csr.Close(ctx)

Next, we will save the query result data into variables which we will later send to the main function.

go
 1result := make([]Album, 0)
 2for csr.Next(ctx) {
 3  var row Album
 4  err := csr.Decode(&row)
 5  if err != nil {
 6    log.Fatal(err.Error())
 7  }
 8
 9  result = append(result, row)
10}
11
12if len(result) > 0 {
13  fmt.Println("Title  :", result[0].Title)
14  fmt.Println("Artist :", result[0].Artist)
15  fmt.Println("Price  :", result[0].Price)
16}

Displays the entire album data

In this function we want to retrieve all the data in the album collection so that it can be displayed in its entirety.

go
 1func findall() {
 2	ctx := context.Background()
 3	db, err := connect()
 4	if err != nil {
 5		log.Fatal(err.Error())
 6	}
 7
 8	csr, err := db.Collection("album").Find(ctx, bson.D{})
 9	if err != nil {
10		log.Fatal(err.Error())
11	}
12	defer csr.Close(ctx)
13
14	result := make([]Album, 0)
15	for csr.Next(ctx) {
16		var row Album
17		err := csr.Decode(&row)
18		if err != nil {
19			log.Fatal(err.Error())
20		}
21
22		result = append(result, row)
23	}
24
25	if len(result) > 0 {
26		for _, res := range result {
27			fmt.Println("Title  :", res.Title)
28			fmt.Println("Artist :", res.Artist)
29			fmt.Println("Price  :", res.Price)
30		}
31	}
32}

We will call the same function as above but the function output in this function produces the Album struct array

Change album data

When we want to change album data, here we need to choose which ID we want to update so that it can be accepted. The following is a function to update the MongoDB database collection.

go
 1func update() {
 2	ctx := context.Background()
 3	db, err := connect()
 4	if err != nil {
 5		log.Fatal(err.Error())
 6	}
 7
 8	var selector = bson.M{"id": 2}
 9	var changes = Album{ID: 2, Title: "Bintang Di surga", Artist: "Peterpan", Price: 60000}
10	_, err = db.Collection("album").UpdateOne(ctx, selector, bson.M{"$set": changes})
11	if err != nil {
12		log.Fatal(err.Error())
13	}
14
15	fmt.Println("Update success!")
16}

Different from the query above, for the update function we need to set a selector so that we know which data we will update. Then continue with the changes that we will update

go
1var selector = bson.M{"id": 2}
2var changes = Album{ID: 2, Title: "Bintang Di surga", Artist: "Peterpan", Price: 60000}

After that, we use the UpdateOne function to update the MongoDB database.

go
1_, err = db.Collection("album").UpdateOne(ctx, selector, bson.M{"$set": changes})
2if err != nil {
3  log.Fatal(err.Error())
4}

Delete Album Data

The next function is that we add the delete album function. In this case we want to delete the ID 2 collection data with the complete function below.

go
 1func remove() {
 2	ctx := context.Background()
 3	db, err := connect()
 4	if err != nil {
 5		log.Fatal(err.Error())
 6	}
 7
 8	var selector = bson.M{"id": 2}
 9	_, err = db.Collection("album").DeleteOne(ctx, selector)
10	if err != nil {
11		log.Fatal(err.Error())
12	}
13
14	fmt.Println("Remove success!")
15}

As with updates, we also need to decide which one we will update. The example here is using bson.M{"id", 2} which we will delete. Next, we execute it with the DeleteOne function.

go
1var selector = bson.M{"id": 2}
2_, err = db.Collection("album").DeleteOne(ctx, selector)
3if err != nil {
4  log.Fatal(err.Error())
5}

OK, we have defined all the functions, we just need to call each function that we have defined into the main function which we will execute in the future.

Related Articles

💬 Comments