Programming

How To Communication Golang with MongoDB

Dependecy Needed

Add some dependency when we used

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"

Create a Database Connection

create database connection function into mongoDB.

func connect() (*mongo.Database, error) {
	clientOptions := options.Client()
	clientOptions.ApplyURI("mongodb+srv://test:test@cluster0.awkve.mongodb.net/?retryWrites=true&w=majority")
	client, err := mongo.NewClient(clientOptions)
	if err != nil {
		return nil, err
	}

	err = client.Connect(context.Background())
	if err != nil {
		return nil, err
	}

	return client.Database("recordings"), nil
}

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

clientOptions := options.Client()
clientOptions.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.

client, err := mongo.NewClient(clientOptions)
if err != nil {
  return nil, err
}

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

err = client.Connect(context.Background())
if err != nil {
  return nil, err
}

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

return 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.

func insert() {
	db, err := connect()
	if err != nil {
		log.Fatal(err.Error())
	}

	ctx := context.Background()

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

	_, err = db.Collection("album").InsertOne(ctx, Album{ID: 2, Title: "Sebuah Nama Sebuah Cerita", Artist: "Peterpan", Price: 50000})
	if err != nil {
		log.Fatal(err.Error())
	}

	fmt.Println("Insert success!")
}

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

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

Create Displays albums

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

func find() {
	ctx := context.Background()
	db, err := connect()
	if err != nil {
		log.Fatal(err.Error())
	}

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

	result := make([]Album, 0)
	for csr.Next(ctx) {
		var row Album
		err := csr.Decode(&row)
		if err != nil {
			log.Fatal(err.Error())
		}

		result = append(result, row)
	}

	if len(result) > 0 {
		fmt.Println("Title  :", result[0].Title)
		fmt.Println("Artist :", result[0].Artist)
		fmt.Println("Price  :", result[0].Price)
	}
}

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.

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

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

defer csr.Close(ctx)

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

result := make([]Album, 0)
for csr.Next(ctx) {
  var row Album
  err := csr.Decode(&row)
  if err != nil {
    log.Fatal(err.Error())
  }

  result = append(result, row)
}

if len(result) > 0 {
  fmt.Println("Title  :", result[0].Title)
  fmt.Println("Artist :", result[0].Artist)
  fmt.Println("Price  :", result[0].Price)
}

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.

func findall() {
	ctx := context.Background()
	db, err := connect()
	if err != nil {
		log.Fatal(err.Error())
	}

	csr, err := db.Collection("album").Find(ctx, bson.D{})
	if err != nil {
		log.Fatal(err.Error())
	}
	defer csr.Close(ctx)

	result := make([]Album, 0)
	for csr.Next(ctx) {
		var row Album
		err := csr.Decode(&row)
		if err != nil {
			log.Fatal(err.Error())
		}

		result = append(result, row)
	}

	if len(result) > 0 {
		for _, res := range result {
			fmt.Println("Title  :", res.Title)
			fmt.Println("Artist :", res.Artist)
			fmt.Println("Price  :", res.Price)
		}
	}
}

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.

func update() {
	ctx := context.Background()
	db, err := connect()
	if err != nil {
		log.Fatal(err.Error())
	}

	var selector = bson.M{"id": 2}
	var changes = Album{ID: 2, Title: "Bintang Di surga", Artist: "Peterpan", Price: 60000}
	_, err = db.Collection("album").UpdateOne(ctx, selector, bson.M{"$set": changes})
	if err != nil {
		log.Fatal(err.Error())
	}

	fmt.Println("Update success!")
}

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

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

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

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

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.

func remove() {
	ctx := context.Background()
	db, err := connect()
	if err != nil {
		log.Fatal(err.Error())
	}

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

	fmt.Println("Remove success!")
}

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.

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

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.

comments powered by Disqus