Go lang
Programs
read csv file
find variable type in golang
for loops in golang
MongoDB sort() Method
MongoDB Find
MongoDB FindOne
differences between arrays and slices
InsertOne MongoDB
Connecting to MongoDB
how to use range in golang
Modules
Create a Go module
Create app using Go Module
Install
Installing GO lang

Insert Data Into MongoDB



Introduction

In this Tutorial we will connect to MongoDB, and then insert a document in MongoDB


initialize go module, by issuing the below command
go mod init github.com/freedomtutorials/mongodbinsert

import go drivers into application, by issuing the below command
go get go.mongodb.org/mongo-driver

Define a type which is identical to golang document

type Device struct 
{
	ID int
	Name string
}


Connect to MongoDB

Below is the Go lang Code, which connects to MongoDB database.

    // set the mongodb uri 
    clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
	
    //connect to mongodb
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
        log.Fatal(err)
    }

    err = client.Ping(context.TODO(), nil)

    if err != nil {
        log.Fatal(err)
    }

Get handle to database through client connection.

freedomtutorialsDB := client.Database("freedomtutorials")

Get handle to collection through database handle.

mydataCollection := freedomtutorialsDB.Collection("mydata")

create instance of type and fill data

	var device Device
	device.ID = 1
	device.Name = "Name"

Now Insert data with mydataCollection instance and pass the data object as parameter.

collInsertResult, err := mydataCollection.InsertOne(context.TODO(), device)

check for errors in InsertOne Operation

if err != nil {
    log.Fatal(err)
}

print InsertedID

fmt.Println("Inserted Single Document: ", collInsertResult.InsertedID)


how to use range in golang

how to use range in golang

posted on 2022-05-03 08:28:11 - Go lang Tutorials


find variable type in golang

find variable type in golang

posted on 2022-05-03 05:24:55 - Go lang Tutorials


for loops in golang

for loops in golang

posted on 2022-05-03 04:27:40 - Go lang Tutorials


Run MongoDB On WSL Ubuntu

Run MongoDB On WSL Ubuntu

posted on 2022-04-28 05:02:09 - mongodb Tutorials


Installing MongoDB

Installing MongoDB

posted on 2022-04-28 04:16:57 - mongodb Tutorials


MySQL TRIGGERS

MySQL - Triggers

posted on 2019-11-29 21:44:07 - mysql Tutorials