create application directory
go mod init github.com/freedomtutorials/mongodbfindone
import mongodb-drivers
go get go.mongodb.org/mongo-driver
Connect to MongoDB, with 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")
FindOne document on collection
var device Device
if err = mydataCollection.FindOne( context.TODO(), bson.M{}).Decode(&device); err != nil {
log.Fatal(err)
}
fmt.Println(device)
output:
{1 Name}
FindOne document on collection with filter
if err = mydataCollection.FindOne( context.TODO(), bson.M{"id":1}).Decode(&device); err != nil {
log.Fatal(err)
}
fmt.Println(device)
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