https://github.com/cloudresty/go-mongodb
A modern, production-ready Go package for MongoDB operations with environment-first configuration, ULID ObjectIDs, and comprehensive production features
https://github.com/cloudresty/go-mongodb
Last synced: 4 months ago
JSON representation
A modern, production-ready Go package for MongoDB operations with environment-first configuration, ULID ObjectIDs, and comprehensive production features
- Host: GitHub
- URL: https://github.com/cloudresty/go-mongodb
- Owner: cloudresty
- License: mit
- Created: 2025-06-30T15:33:13.000Z (about 1 year ago)
- Default Branch: main
- Last Pushed: 2026-03-09T03:16:11.000Z (4 months ago)
- Last Synced: 2026-03-09T08:27:32.795Z (4 months ago)
- Language: Go
- Homepage: https://cloudresty.com
- Size: 306 KB
- Stars: 2
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE.txt
- Security: SECURITY.md
Awesome Lists containing this project
README
# Go MongoDB
[Home](README.md) /
A modern, production-ready Go package for MongoDB operations with environment-first configuration, ULID IDs, and comprehensive production features.
[](https://pkg.go.dev/github.com/cloudresty/go-mongodb/v2)
[](https://github.com/cloudresty/go-mongodb/actions/workflows/ci.yaml)
[](https://goreportcard.com/report/github.com/cloudresty/go-mongodb/v2)
[](https://github.com/cloudresty/go-mongodb/tags)
[](https://opensource.org/licenses/MIT)
## Table of Contents
- [Key Features](#key-features)
- [Quick Start](#quick-start)
- [Installation](#installation)
- [Basic Usage](#basic-usage)
- [Environment Configuration](#environment-configuration)
- [Documentation](#documentation)
- [Why This Package?](#why-this-package)
- [Production Usage](#production-usage)
- [Requirements](#requirements)
- [Contributing](#contributing)
- [Security](#security)
- [License](#license)
## Key Features
- **Environment-First**: Configure via environment variables for cloud-native deployments
- **ULID IDs**: 6x faster generation, database-optimized, lexicographically sortable
- **Zero-Allocation ID Injection**: Best-in-class performance for struct inserts
- **Production-Ready**: Graceful shutdown, timeouts, health checks, transaction support
- **Type-Safe API**: Strict validation prevents data corruption
- **Pluggable Logging**: Silent by default, integrate with any logging framework
- **Command Monitoring**: Built-in APM support for Datadog, OpenTelemetry, etc.
- **Fully Tested**: Comprehensive test coverage with CI/CD pipeline
🔝 [back to top](#go-mongodb)
## Quick Start
### Installation
```bash
go get github.com/cloudresty/go-mongodb/v2
```
> **Note**: This is v2 of the library. For migration from v1, see [Migration Guide](docs/migration-v2.md).
🔝 [back to top](#go-mongodb)
### Basic Usage
```go
package main
import (
"context"
"log"
"github.com/cloudresty/go-mongodb/v2"
"github.com/cloudresty/go-mongodb/v2/filter"
"github.com/cloudresty/go-mongodb/v2/update"
)
type User struct {
Name string `bson:"name" json:"name"`
Email string `bson:"email" json:"email"`
Status string `bson:"status" json:"status"`
}
func main() {
// Client - uses MONGODB_* environment variables
client, err := mongodb.NewClient()
if err != nil {
panic(err)
}
defer client.Close()
// Insert a document with auto-generated ULID ID using type-safe struct
collection := client.Collection("users")
user := User{
Name: "John Doe",
Email: "john@example.com",
}
result, err := collection.InsertOne(context.Background(), user)
if err != nil {
log.Fatal(err)
}
// Find documents using type-safe filter
var foundUser User
err = collection.FindOne(context.Background(),
filter.Eq("email", "john@example.com")).Decode(&foundUser)
if err != nil {
log.Fatal(err)
}
// Update documents using type-safe update builder
_, err = collection.UpdateOne(context.Background(),
filter.Eq("email", "john@example.com"),
update.Set("status", "active"))
if err != nil {
log.Fatal(err)
}
}
```
🔝 [back to top](#go-mongodb)
### Environment Configuration
Set environment variables for your deployment:
```bash
export MONGODB_HOSTS=localhost:27017
export MONGODB_DATABASE=myapp
export MONGODB_CONNECTION_NAME=my-service
```
🔝 [back to top](#go-mongodb)
## Documentation
| Document | Description |
| :--- | :--- |
| [Getting Started](docs/getting-started.md) | Quick start guide and installation instructions |
| [Migration Guide v2](docs/migration-v2.md) | Migrating from v1 to v2 |
| [API Reference](docs/api-reference.md) | Complete function reference and usage patterns |
| [Environment Variables](docs/environment-variables.md) | Supported variables and their purpose |
| [Environment Configuration](docs/environment-configuration.md) | Environment variables and deployment configurations |
| [Production Features](docs/production-features.md) | Graceful shutdown, health checks, transactions |
| [ID Generation](docs/id-generation.md) | High-performance, database-optimized document identifiers |
| [Examples](docs/examples.md) | Comprehensive examples and usage patterns |
🔝 [back to top](#go-mongodb)
## Why This Package?
This package is designed for modern cloud-native applications that require robust, high-performance MongoDB operations. It leverages the power of MongoDB while providing a developer-friendly API that integrates seamlessly with environment-based configurations.
🔝 [back to top](#go-mongodb)
### Environment-First Design
Perfect for modern cloud deployments with Docker, Kubernetes, and CI/CD pipelines. No more hardcoded connection strings.
🔝 [back to top](#go-mongodb)
### ULID IDs
Get 6x faster document ID generation with better database performance compared to UUIDs. Natural time-ordering and collision resistance.
🔝 [back to top](#go-mongodb)
### Production-Ready
Built-in support for high availability, graceful shutdown, automatic reconnection, and comprehensive timeout controls.
🔝 [back to top](#go-mongodb)
### Performance Optimized
Pluggable logging framework, efficient ULID generation, and optimized for high-throughput scenarios.
🔝 [back to top](#go-mongodb)
## Production Usage
```go
package main
import (
"context"
"log"
"time"
"github.com/cloudresty/go-mongodb/v2"
)
func main() {
// Use custom environment prefix for multi-service deployments
client, err := mongodb.NewClient(mongodb.FromEnvWithPrefix("PAYMENTS_"))
if err != nil {
log.Fatal(err)
}
defer client.Close()
// Or configure with custom logger (silent by default)
// client, err := mongodb.NewClient(
// mongodb.FromEnv(),
// mongodb.WithLogger(yourCustomLogger), // Implement mongodb.Logger interface
// )
// Health checks and monitoring - use Ping to verify connectivity
if err := client.Ping(context.Background()); err != nil {
log.Fatalf("Health check failed: MongoDB is not reachable: %v", err)
}
log.Println("Health check passed: MongoDB is reachable.")
// For detailed metrics, get the stats
stats := client.Stats()
log.Printf("Client stats: %+v", stats)
// Graceful shutdown with signal handling
shutdownManager := mongodb.NewShutdownManager(&mongodb.ShutdownConfig{
Timeout: 30 * time.Second,
})
shutdownManager.SetupSignalHandler()
shutdownManager.Register(client)
shutdownManager.Wait() // Blocks until SIGINT/SIGTERM
}
```
🔝 [back to top](#go-mongodb)
## Requirements
- Go 1.24+ (recommended)
- MongoDB 8.0+ (recommended)
🔝 [back to top](#go-mongodb)
## Contributing
We welcome contributions! Please see our [Contributing Guidelines](CONTRIBUTING.md) for details.
1. Fork the repository
2. Create a feature branch
3. Add tests for your changes
4. Ensure all tests pass
5. Submit a pull request
🔝 [back to top](#go-mongodb)
## Security
If you discover a security vulnerability, please report it via email to [security@cloudresty.com](mailto:security@cloudresty.com).
🔝 [back to top](#go-mongodb)
## License
This project is licensed under the MIT License - see the [LICENSE.txt](LICENSE.txt) file for details.
🔝 [back to top](#go-mongodb)
---
### Cloudresty
[Website](https://cloudresty.com) | [LinkedIn](https://www.linkedin.com/company/cloudresty) | [BlueSky](https://bsky.app/profile/cloudresty.com) | [GitHub](https://github.com/cloudresty) | [Docker Hub](https://hub.docker.com/u/cloudresty)
© Cloudresty