Go lang
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
Create a Go module
Create app using Go Module
Installing GO lang

Insert Data Into MongoDB


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://")
    //connect to mongodb
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {

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

    if err != nil {

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 {

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

Prompt Examples

ChatGPT Prompt Examples

posted on 2023-06-21 22:37:19 - ChatGPT Tutorials

Use Cases

Chat GPT Key Use Cases

posted on 2023-06-21 21:03:17 - ChatGPT Tutorials

Prompt Frameworks

Prompt Frameworks

posted on 2023-06-21 19:33:06 - ChatGPT Tutorials