In this Tutorial we will connect to MongoDB, and then insert a document in MongoDB
go mod init github.com/freedomtutorials/mongodbinsert
go get go.mongodb.org/mongo-driver
type Device struct
{
ID int
Name string
}
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
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