Create Database
Create a database with the name is learn_mongodb_golang. This database have a collection: Product collection.
/* Create learn_mongodb_golang database */
use learn_mongodb_golang
/* Create Product collection */
db.createCollection('product');
/* Dumping data for `product` collection */
db.getCollection('product').insert({
"name" : "Mobile 1",
"price" : 45.0,
"quantity" : 4.0,
"status" : true,
"date" : ISODate("2016-10-20T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"red",
"green",
"blue"
]
});
db.getCollection('product').insert({
"name" : "Mobile 2",
"price" : 12.0,
"quantity" : 7.0,
"status" : true,
"date" : ISODate("2017-11-14T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 2"
},
"colors" : [
"yellow",
"green"
]
});
db.getCollection('product').insert({
"name" : "Mobile 3",
"price" : 28.0,
"quantity" : 8.0,
"status" : true,
"date" : ISODate("2017-11-20T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711668"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 3"
},
"colors" : [
"black",
"blue"
]
});
db.getCollection('product').insert({
"name" : "Laptop 1",
"price" : 39.0,
"quantity" : 12.0,
"status" : false,
"date" : ISODate("2017-12-26T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711669"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue"
]
});
db.getCollection('product').insert({
"name" : "Laptop 2",
"price" : 86.0,
"quantity" : 23.0,
"status" : true,
"date" : ISODate("2017-03-11T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa45711669"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue",
"yellow"
]
});
db.getCollection('product').insert({
"name" : "Tivi 1",
"price" : 22.0,
"quantity" : 7.0,
"status" : true,
"date" : ISODate("2017-06-26T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa4571166a"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 1"
},
"colors" : [
"blue",
"white",
"black"
]
});
db.getCollection('product').insert({
"name" : "Tivi 2",
"price" : 86.0,
"quantity" : 23.0,
"status" : false,
"date" : ISODate("2017-09-24T00:00:00.000Z"),
"categoryId" : ObjectId("5a30de130867edfa4571166a"),
"brand" : {
"_id" : new ObjectId(),
"name" : "brand 3"
},
"colors" : [
"red",
"green"
]
});
Installing Libraries
Install MGO library as below:
go get gopkg.in/mgo.v2
Configuration
In src folder, create new folder named config. In this folder, create new file named config.go, this file is used to connect to mongodb database:
package config
import (
mgo "gopkg.in/mgo.v2"
)
func GetMongoDB() (*mgo.Database, error) {
host := "mongodb://localhost:27017"
dbName := "learn_mongodb_golang"
session, err := mgo.Dial(host)
if err != nil {
return nil, err
}
db := session.DB(dbName)
return db, nil
}
Entity Classes
Create new folder named entities. In this folder, create new go files as below:
Brand Entity
In entities folder, create new go file named brand_entity.go as below:
package entities
import (
"fmt"
"gopkg.in/mgo.v2/bson"
)
type Brand struct {
Id bson.ObjectId `bson:"_id"`
Name string `bson:"name"`
}
func (this Brand) ToString() string {
result := fmt.Sprintf("\nbrand id: %s", this.Id.Hex())
result = result + fmt.Sprintf("\nbrand name: %s", this.Name)
return result
}
Product Entity
In entities folder, create new go file named product_entity.go as below:
package entities
import (
"fmt"
"strings"
"time"
"gopkg.in/mgo.v2/bson"
)
type Product struct {
Id bson.ObjectId `bson:"_id"`
Name string `bson:"name"`
Price float64 `bson:"price"`
Quantity int64 `bson:"quantity"`
Status bool `bson:"status"`
Date time.Time `bson:"date"`
CategoryId bson.ObjectId `bson:"categoryId"`
Brand Brand `bson:"brand"`
Colors []string `bson:"colors"`
}
func (this Product) ToString() string {
result := fmt.Sprintf("id: %s", this.Id.Hex())
result = result + fmt.Sprintf("\nname: %s", this.Name)
result = result + fmt.Sprintf("\nprice: %0.1f", this.Price)
result = result + fmt.Sprintf("\nquantity: %d", this.Quantity)
result = result + fmt.Sprintf("\nstatus: %t", this.Status)
result = result + fmt.Sprintf("\ndate: %s", this.Date.Format("2006-01-02"))
result = result + fmt.Sprintf("\ncategory id: %s", this.Category.Hex())
result = result + this.Brand.ToString()
result = result + fmt.Sprintf("\ncolors: %s", strings.Join(this.Colors, ", "))
return result
}
Models
In src folder, create new folder named models. In models folder, create new file named product_model.go. This file contains methods to interact with the database.
package models
import (
"config"
"entities"
)
type ProductModel struct {
}
func (this ProductModel) Create(product *entities.Product) error {
db, err := config.GetMongoDB()
if err != nil {
return err
} else {
return db.C("product").Insert(&product)
}
}
Structure of Project
Run Application
In src folder, create new file named main.go and use command go run main.go run application:
package main
import (
"entities"
"fmt"
"models"
"time"
"gopkg.in/mgo.v2/bson"
)
func main() {
var productModel models.ProductModel
product := entities.Product{
Id: bson.NewObjectId(),
Name: "Tivi 3",
Price: 11.5,
Quantity: 4,
Status: true,
Date: time.Now(),
CategoryId: bson.NewObjectId(),
Brand: entities.Brand{
Id: bson.NewObjectId(),
Name: "Brand 2",
},
Colors: []string{
"red", "blue",
},
}
err := productModel.Create(&product)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(product.ToString())
}
}
Output
id: 5ce024153c9cb135b4074c75
name: Tivi 3
price: 11.5
quantity: 4
status: true
date: 2019-05-18
category id: 5ce024153c9cb135b4074c76
brand id: 5ce024153c9cb135b4074c77
brand name: Brand 2
colors: red, blue