MongoDB InsertOne – GinGonic Golang Framework 15
MongoDB InsertOne – GinGonic Golang Framework 15
[sourcecode lang=”go” autolinks=”false” classname=”myclass” collapse=”false” firstline=”1″ gutter=”true” highlight=”1-3,6,9″ htmlscript=”false” light=”false” padlinenumbers=”false” smarttabs=”true” tabsize=”4″ toolbar=”false” title=”Source Code main.go”]// 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()
}
[/sourcecode]
golang gingonic framework videos tutorials series
TAGS#
gin gonic tutorial
gin-gonic / examples
gin-gonic documentation
gin framework tutorial
gin web framework
gin router
golang gin context
gin router group