MongoDB Example
This project demonstrates how to connect to a MongoDB database in a Go application using the Fiber framework.
Prerequisites
Ensure you have the following installed:
- Golang
- Fiber package
- MongoDB
- MongoDB Go Driver
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.gitcd recipes/mongodb -
Install dependencies:
go get -
Start MongoDB using Docker:
docker-compose up -d -
(Optional) Set the
MONGO_URIenvironment variable. Defaults tomongodb://localhost:27017/fiber_test:export MONGO_URI="mongodb://localhost:27017/fiber_test"
Running the Application
- Start the application:
go run main.go
Example
Here is an example of how to connect to a MongoDB database in a Fiber application:
package main
import (
"context"
"log"
"time"
"github.com/gofiber/fiber/v3"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// MongoDB connection
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client, err := mongo.Connect(ctx, options.Client().ApplyURI("mongodb://localhost:27017"))
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(context.Background())
// Fiber instance
app := fiber.New()
// Routes
app.Get("/", func(c fiber.Ctx) error {
return c.SendString("Hello, MongoDB!")
})
// Start server
log.Fatal(app.Listen(":3000"))
}