golang gingonic framework videos tutorials series

MongoDB InsertOne – GinGonic Golang Framework 15

MongoDB InsertOne – GinGonic Golang Framework 15

 

// Mongodb & GinGonic 🙂
//go get go.mongodb.org/mongo-driver/mongo
// install driver first
package main
import (
    "context"
    "github.com/gin-gonic/gin"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)
// context variable
var ctx = context.TODO()
var collection *mongo.Collection
// lets create collection global variable
// lets connect & initialize mongodb first
func init() {
    // it need 2 parameters
    //context & url of database
    client, _ := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
    //we ignored error 🙂
    // lets create database and collection(table)
    collection = client.Database("anyname").Collection("anyname")
}
func main() {
    // lets create our gingonic server
    r := gin.Default()
    r.GET("/", func(c *gin.Context) {
        // this is our first route
        // lets insert data into database
        // it need 2 parameters context & value in bson.D format
        // bson.D is actualy key value pair
        // bson.D{{"key1","value1"},{"key2","value2"}}
        // and so on....
        result, _ := collection.InsertOne(ctx,
            bson.D{{"name", "indo"}, {"value", 00007}})
        // display output in json / string or any format
        c.JSON(200, result)
    })
    r.Run()
}

TAGS#

gin gonic tutorial
gin-gonic / examples
gin-gonic documentation
gin framework tutorial
gin web framework
gin router
golang gin context
gin router group

Tony BB
 

TonyBB is a Coach , marketer, hypnotist and a founder of RSKVF Production who specializes in providing simple, affordable, and easy to use solutions for Life.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: