MongoDB InsertOne – GinGonic Golang Framework 15

MongoDB InsertOne – GinGonic Golang Framework 15


Source Code

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




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: