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

MongoDB Find using golang



MongoDB Find using golang

This article explains how to use MongoDB Find method in Golong using mongodb-drivers


create application directory for golang application, and create init go module as below

mkdir mongodbfind
cd mongodbfind
go mod init github.com/freedomtutorials/mongodbfind

import mongodb-drivers in go module, for this issue the below command

go get go.mongodb.org/mongo-driver

Connect to MongoDB, using below code

    // 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)
    }

    fmt.Println("Connected to MongoDB!")

    freedomtutorialsDB := client.Database("freedomtutorials")
    mydataCollection := freedomtutorialsDB.Collection("mydata")


Reading All Documents from a Collection using cursor.All


	cursor, err := mydataCollection.Find( context.TODO(), bson.M{})
	if err != nil {
		log.Fatal(err)
	}

	var device []Device
	if err = cursor.All( context.TODO(), &device); err != nil {
		log.Fatal(err)
	}
	fmt.Println(device)

or we can Read one document at a time from cursor and append to slice


	cursor, err := mydataCollection.Find( context.TODO(), bson.M{})
	if err != nil {
		log.Fatal(err)
	}

	for cursor.Next( context.TODO()) {
		var device Device
		if err = cursor.Decode( &device); err != nil {
			log.Fatal(err)
		}
		devices = append( devices, device)
	}
	
	fmt.Println(devices)

close the cursor

cursor.Close( context.TODO())

code can be download from below Github URL


https://github.com/freedomtutorials/mongodbfind

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