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
how to use range in golang
posted on 2022-05-03 08:28:11 - Go lang Tutorials
find variable type in golang
posted on 2022-05-03 05:24:55 - Go lang Tutorials