DEV Community

Discussion on: Go and MongoDB: Building a CRUD API from Scratch

Collapse
 
adegoodyer profile image
Adrian Goodyer

Great article Mohd, congrats!

Which tool would yourself (or anyone else) recommend to manage migrations with Go and MongoDB?

Atlas and Goose are my preference, but are SQL focused so I use go-migrations - but the migrations are written in JSON and I'd really like to write the migrations in Go instead!

Collapse
 
aquibpy profile image
Mohd Aquib

To manage MongoDB migrations in Go without using JSON, use the migrate library with the MongoDB driver and write migrations programmatically in Go. Here’s a concise guide:

Install dependencies:

   go get -u -d github.com/golang-migrate/migrate/cmd/migrate
   go get -u github.com/golang-migrate/migrate/v4/database/mongodb
   go get -u github.com/golang-migrate/migrate/v4/source/file
Enter fullscreen mode Exit fullscreen mode

Create a migration in Go:

   package main

   import (
       "github.com/golang-migrate/migrate/v4"
       "github.com/golang-migrate/migrate/v4/database/mongodb"
       "github.com/golang-migrate/migrate/v4/source/file"
       "log"
   )

   func main() {
       mongoURL := "mongodb://localhost:27017/mydatabase"

       source, err := (&file.File{}).Open("file://path/to/migrations")
       if err != nil {
           log.Fatal(err)
       }

       database, err := mongodb.WithInstance(mongoURL, &mongodb.Config{})
       if err != nil {
           log.Fatal(err)
       }

       m, err := migrate.NewWithInstance(
           "file",
           source,
           "mongodb",
           database,
       )
       if err != nil {
           log.Fatal(err)
       }

       if err := m.Up(); err != nil && err != migrate.ErrNoChange {
           log.Fatal(err)
       }

       log.Println("Migrations applied successfully!")
   }
Enter fullscreen mode Exit fullscreen mode

Write migrations as Go scripts.

This setup allows you to handle MongoDB migrations using Go code.

Collapse
 
emmanuel_soetan_bc4a8f945 profile image
Emmanuel Soetan

Ever since I learned about goose I have used goose for migrations for PostgreSQL. I feel it gives me more control.