To interact with NoSQL databases like MongoDB using Go, you can use the official MongoDB Go driver called "mongo-go-driver". Follow the steps below to get started:
Install the MongoDB driver:
go get go.mongodb.org/mongo-driver
Import the required packages in your Go code:
import (
"context"
"log"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
Initialize the MongoDB client:
clientOptions := options.Client().ApplyURI("mongodb://localhost:27017")
client, err := mongo.Connect(context.TODO(), clientOptions)
if err != nil {
log.Fatal(err)
}
// Ping the server to check the connection
err = client.Ping(context.TODO(), nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB!")
Use the MongoDB client to interact with the database and collections:
collection := client.Database("mydb").Collection("mycollection")
// Insert a document
document := bson.D{
{Key: "name", Value: "John"},
{Key: "age", Value: 30},
}
_, err = collection.InsertOne(context.TODO(), document)
if err != nil {
log.Fatal(err)
}
// Query documents
filter := bson.D{{Key: "name", Value: "John"}}
var result bson.M
err = collection.FindOne(context.TODO(), filter).Decode(&result)
if err != nil {
log.Fatal(err)
}
fmt.Println("Document:", result)
// Update a document
update := bson.D{{Key: "$set", Value: bson.D{{Key: "age", Value: 31}}}}
_, err = collection.UpdateOne(context.TODO(), filter, update)
if err != nil {
log.Fatal(err)
}
// Delete a document
_, err = collection.DeleteOne(context.TODO(), filter)
if err != nil {
log.Fatal(err)
}
Remember to handle errors appropriately in your code for real-world scenarios.