Library Usage Example
This directory contains a standalone example of how to use mongork as a library in your own Go projects.
What's Included
main.go - Complete example showing how to:
- Load configuration
- Connect to MongoDB
- Create and register migrations
- Run migrations up/down
- Check migration status
How to Use
1. Build the Example
# From the mongork root directory
go build -o examples/library-example/library-example examples/library-example/main.go
# Or using make
make test-examples
2. Run the Example
# Set required environment variables first
export MONGO_URL="mongodb://localhost:27017"
export MONGO_DATABASE="example_db"
# Run the example
./examples/library-example/library-example
3. Use in Your Own Project
# Initialize your Go module
go mod init your-project-name
# Add mongork dependency
go get github.com/drewjocham/mongork@latest
# Copy and adapt the example code from main.go
Example Migration
The example includes a sample migration that:
- Creates a
sample_collection with a document
- Adds an index on
created_at
- Demonstrates rollback by dropping the collection
Configuration
The example uses environment variables or falls back to default values:
MONGO_URL - MongoDB connection string (default: mongodb://localhost:27017)
MONGO_DATABASE - Database name (default: standalone_example)
MIGRATIONS_COLLECTION - Collection for migration tracking (default: schema_migrations)
Output
When run successfully, you'll see:
π mongork Standalone Example
=====================================
βΉοΈ Using default configuration (no .env file found)
π Connecting to MongoDB: mongodb://localhost:27017/standalone_example
β
Connected to MongoDB successfully
π Migration Status:
20240109_001 β No Example migration - creates sample_collection with index
β¬οΈ Running migrations up...
β
Created sample_collection with index
β
All migrations applied successfully
π Updated Migration Status:
20240109_001 β
Yes Example migration - creates sample_collection with index
β¬οΈ Rolling back last migration...
β
Dropped sample_collection
β
Rolled back migration: 20240109_001
π Standalone example completed successfully!
This demonstrates the complete lifecycle of using mongork as a library.