mongodb

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 25, 2025 License: MIT Imports: 17 Imported by: 0

README

Go MongoDB

Home  /

 

A modern, production-ready Go package for MongoDB operations with environment-first configuration, ULID IDs, and comprehensive production features.

 

Go Reference Go Tests Go Report Card GitHub Tag License

 

Table of Contents

 

Key Features

  • Environment-First: Configure via environment variables for cloud-native deployments
  • ULID IDs: 6x faster generation, database-optimized, lexicographically sortable
  • Auto-Reconnection: Intelligent retry with configurable backoff
  • Production-Ready: Graceful shutdown, timeouts, health checks, transaction support
  • High Performance: Zero-allocation logging, optimized for throughput
  • Fully Tested: Comprehensive test coverage with CI/CD pipeline

🔝 back to top

 

Quick Start

 

Installation
go get github.com/cloudresty/go-mongodb

🔝 back to top

 

Basic Usage
package main

import (
    "context"
    "github.com/cloudresty/go-mongodb"
)

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
    collection := client.Collection("users")
    result, err := collection.InsertOne(context.Background(), map[string]any{
        "name":  "John Doe",
        "email": "john@example.com",
    })

    // Find documents
    var user map[string]any
    err = collection.FindOne(context.Background(), map[string]any{
        "email": "john@example.com",
    }).Decode(&user)

    // Update documents
    _, err = collection.UpdateOne(context.Background(),
        map[string]any{"email": "john@example.com"},
        map[string]any{"$set": map[string]any{"status": "active"}},
    )
}

🔝 back to top

 

Environment Configuration

Set environment variables for your deployment:

export MONGODB_HOST=localhost
export MONGODB_PORT=27017
export MONGODB_DATABASE=myapp
export MONGODB_CONNECTION_NAME=my-service

🔝 back to top

 

Documentation

Document Description
API Reference Complete function reference and usage patterns
Environment Configuration Environment variables and deployment configurations
Production Features Auto-reconnection, graceful shutdown, health checks, transactions
ULID IDs High-performance, database-optimized document identifiers
Examples Comprehensive examples and usage patterns

🔝 back to top

 

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

 

Environment-First Design

Perfect for modern cloud deployments with Docker, Kubernetes, and CI/CD pipelines. No more hardcoded connection strings.

🔝 back to top

 

ULID IDs

Get 6x faster document ID generation with better database performance compared to UUIDs. Natural time-ordering and collision resistance.

🔝 back to top

 

Production-Ready

Built-in support for high availability, graceful shutdown, automatic reconnection, and comprehensive timeout controls.

🔝 back to top

 

Performance Optimized

Zero-allocation logging, efficient ULID generation, and optimized for high-throughput scenarios.

🔝 back to top

 

Production Usage

// Use custom environment prefix for multi-service deployments
client, err := mongodb.NewClientWithPrefix("PAYMENTS_")

// Health checks and monitoring
if client.IsConnected() {
    health := client.HealthCheck()
    log.Printf("MongoDB health: %+v", health)
}

// 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

 

Requirements

  • Go 1.24+ (recommended)
  • MongoDB 7.0+ (recommended)

🔝 back to top

 

Contributing

We welcome contributions! Please see our Contributing Guidelines 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

 

Security

If you discover a security vulnerability, please report it via email to security@cloudresty.com.

🔝 back to top

 

License

This project is licensed under the MIT License - see the LICENSE.txt file for details.

🔝 back to top

 


 

An open source project brought to you by the Cloudresty team.

Website  |  LinkedIn  |  BlueSky  |  GitHub

 

Documentation

Overview

Package mongodb provides a modern, production-ready Go package for MongoDB operations with environment-first configuration, ULID message IDs, auto-reconnection, and comprehensive production features.

This package follows the same design patterns as the cloudresty/go-rabbitmq package, providing a clean, intuitive API for MongoDB operations while maintaining high performance and production-ready features.

Key Features:

  • Environment-first configuration using cloudresty/go-env
  • ULID-based document IDs for better performance and sorting
  • Auto-reconnection with intelligent retry and exponential backoff
  • Zero-allocation logging with cloudresty/emit
  • Production-ready features (graceful shutdown, health checks, metrics)
  • Simple, intuitive function names following Go best practices
  • Comprehensive error handling and logging
  • Built-in connection pooling and compression
  • Transaction support with helper methods
  • Change streams for real-time data
  • Index management utilities

Environment Variables:

  • MONGODB_HOST: MongoDB server host (default: localhost)
  • MONGODB_PORT: MongoDB server port (default: 27017)
  • MONGODB_USERNAME: Authentication username
  • MONGODB_PASSWORD: Authentication password
  • MONGODB_DATABASE: Database name (required)
  • MONGODB_AUTH_DATABASE: Authentication database (default: admin)
  • MONGODB_REPLICA_SET: Replica set name
  • MONGODB_MAX_POOL_SIZE: Maximum connection pool size (default: 100)
  • MONGODB_MIN_POOL_SIZE: Minimum connection pool size (default: 5)
  • MONGODB_CONNECT_TIMEOUT: Connection timeout (default: 10s)
  • MONGODB_RECONNECT_ENABLED: Enable auto-reconnection (default: true)
  • MONGODB_HEALTH_CHECK_ENABLED: Enable health checks (default: true)
  • MONGODB_COMPRESSION_ENABLED: Enable compression (default: true)
  • MONGODB_READ_PREFERENCE: Read preference (default: primary)
  • MONGODB_APP_NAME: Application name for connection metadata
  • MONGODB_LOG_LEVEL: Logging level (default: info)

Basic Usage:

package main

import (
    "context"
    "github.com/cloudresty/go-mongodb"
)

func main() {
    // Create client using environment variables
    client, err := mongodb.NewClient()
    if err != nil {
        panic(err)
    }
    defer client.Close()

    // Get a collection
    users := client.Collection("users")

    // Insert a document with auto-generated ULID
    result, err := users.InsertOne(context.Background(), bson.M{
        "name":  "John Doe",
        "email": "john@example.com",
    })
    if err != nil {
        panic(err)
    }

    fmt.Printf("Inserted document with ID: %s, ULID: %s\n",
        result.InsertedID.Hex(), result.ULID)
}

Production Usage with Graceful Shutdown:

func main() {
    // Create client with custom environment prefix
    client, err := mongodb.NewClientWithPrefix("PAYMENTS_")
    if err != nil {
        panic(err)
    }

    // Setup graceful shutdown
    shutdownManager := mongodb.NewShutdownManager(&mongodb.ShutdownConfig{
        Timeout: 30 * time.Second,
    })
    shutdownManager.SetupSignalHandler()
    shutdownManager.Register(client)

    // Your application logic here
    // ...

    // Wait for shutdown signal
    shutdownManager.Wait() // Blocks until SIGINT/SIGTERM
}

Transaction Example:

result, err := client.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (any, error) {
    users := client.Collection("users")
    orders := client.Collection("orders")

    // Insert user
    userResult, err := users.InsertOne(sessCtx, bson.M{"name": "John"})
    if err != nil {
        return nil, err
    }

    // Insert order
    orderResult, err := orders.InsertOne(sessCtx, bson.M{
        "user_id": userResult.InsertedID,
        "amount":  100.00,
    })
    if err != nil {
        return nil, err
    }

    return orderResult, nil
})

Index

Constants

View Source
const (
	EnvMongoDBHost                 = "MONGODB_HOST"
	EnvMongoDBPort                 = "MONGODB_PORT"
	EnvMongoDBUsername             = "MONGODB_USERNAME"
	EnvMongoDBPassword             = "MONGODB_PASSWORD"
	EnvMongoDBDatabase             = "MONGODB_DATABASE"
	EnvMongoDBAuthDatabase         = "MONGODB_AUTH_DATABASE"
	EnvMongoDBReplicaSet           = "MONGODB_REPLICA_SET"
	EnvMongoDBMaxPoolSize          = "MONGODB_MAX_POOL_SIZE"
	EnvMongoDBMinPoolSize          = "MONGODB_MIN_POOL_SIZE"
	EnvMongoDBMaxIdleTime          = "MONGODB_MAX_IDLE_TIME"
	EnvMongoDBMaxConnIdleTime      = "MONGODB_MAX_CONN_IDLE_TIME"
	EnvMongoDBConnectTimeout       = "MONGODB_CONNECT_TIMEOUT"
	EnvMongoDBServerSelectTimeout  = "MONGODB_SERVER_SELECT_TIMEOUT"
	EnvMongoDBSocketTimeout        = "MONGODB_SOCKET_TIMEOUT"
	EnvMongoDBReconnectEnabled     = "MONGODB_RECONNECT_ENABLED"
	EnvMongoDBReconnectDelay       = "MONGODB_RECONNECT_DELAY"
	EnvMongoDBMaxReconnectDelay    = "MONGODB_MAX_RECONNECT_DELAY"
	EnvMongoDBReconnectBackoff     = "MONGODB_RECONNECT_BACKOFF"
	EnvMongoDBMaxReconnectAttempts = "MONGODB_MAX_RECONNECT_ATTEMPTS"
	EnvMongoDBHealthCheckEnabled   = "MONGODB_HEALTH_CHECK_ENABLED"
	EnvMongoDBHealthCheckInterval  = "MONGODB_HEALTH_CHECK_INTERVAL"
	EnvMongoDBCompressionEnabled   = "MONGODB_COMPRESSION_ENABLED"
	EnvMongoDBCompressionAlgorithm = "MONGODB_COMPRESSION_ALGORITHM"
	EnvMongoDBReadPreference       = "MONGODB_READ_PREFERENCE"
	EnvMongoDBWriteConcern         = "MONGODB_WRITE_CONCERN"
	EnvMongoDBReadConcern          = "MONGODB_READ_CONCERN"
	EnvMongoDBAppName              = "MONGODB_APP_NAME"
	EnvMongoDBConnectionName       = "MONGODB_CONNECTION_NAME"
	EnvMongoDBIDMode               = "MONGODB_ID_MODE"
	EnvMongoDBLogLevel             = "MONGODB_LOG_LEVEL"
	EnvMongoDBLogFormat            = "MONGODB_LOG_FORMAT"
)

Environment variable names for reference

View Source
const Version = "1.0.0"

Version of the go-mongodb package

Variables

This section is empty.

Functions

func Ascending

func Ascending(fields ...string) bson.D

Ascending creates an ascending sort order

func ByField

func ByField(field string, value any) bson.M

ByField creates a filter for a specific field

func ByFields

func ByFields(fields bson.M) bson.M

ByFields creates a filter for multiple fields

func ByID

func ByID(id any) bson.M

ByID creates a filter for finding by _id

func ByULID

func ByULID(ulid string) bson.M

ByULID creates a filter for finding by ULID

func Descending

func Descending(fields ...string) bson.D

Descending creates a descending sort order

func EnhanceDocument

func EnhanceDocument(doc any) bson.M

EnhanceDocument adds ULID and metadata to a document (uses default ULID mode)

func GenerateULID

func GenerateULID() string

GenerateULID is an alias for NewULID for backward compatibility

func GenerateULIDFromTime

func GenerateULIDFromTime(t time.Time) string

GenerateULIDFromTime generates a ULID with a specific timestamp

func Group

func Group(id any, fields bson.M) bson.M

Group creates a $group stage

func Inc

func Inc(fields bson.M) bson.M

Inc creates a $inc update operation

func IsDuplicateKeyError

func IsDuplicateKeyError(err error) bool

IsDuplicateKeyError checks if an error is a duplicate key error

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError checks if an error is a network-related error

func IsTimeoutError

func IsTimeoutError(err error) bool

IsTimeoutError checks if an error is a timeout error

func Limit

func Limit(n int64) bson.M

Limit creates a $limit stage

func Lookup

func Lookup(from, localField, foreignField, as string) bson.M

Lookup creates a $lookup stage

func Match

func Match(filter bson.M) bson.M

Match creates a $match stage

func NewULID

func NewULID() string

NewULID generates a new ULID string

func Ping

func Ping(ctx ...context.Context) error

Ping tests connectivity to MongoDB using default configuration

func Project

func Project(fields bson.M) bson.M

Project creates a $project stage

func Pull

func Pull(field string, value any) bson.M

Pull creates a $pull update operation

func Push

func Push(field string, value any) bson.M

Push creates a $push update operation

func Set

func Set(fields bson.M) bson.M

Set creates a $set update operation

func Skip

func Skip(n int64) bson.M

Skip creates a $skip stage

func Sort

func Sort(fields bson.D) bson.M

Sort creates a $sort stage

func Unset

func Unset(fields ...string) bson.M

Unset creates an$unset update operation

Types

type A

type A = bson.A

A is an alias for bson.A (array)

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client represents a MongoDB client with auto-reconnection and environment-first configuration

func Connect

func Connect() (*Client, error)

Connect creates a new MongoDB client using environment variables

func ConnectWithConfig

func ConnectWithConfig(config *Config) (*Client, error)

ConnectWithConfig creates a new MongoDB client with the provided configuration

func ConnectWithPrefix

func ConnectWithPrefix(prefix string) (*Client, error)

ConnectWithPrefix creates a new MongoDB client with a custom environment prefix

func MustConnect

func MustConnect() *Client

MustConnect creates a new MongoDB client or panics on error Use this only in main functions or initialization code where panicking is acceptable

func MustConnectWithPrefix

func MustConnectWithPrefix(prefix string) *Client

MustConnectWithPrefix creates a new MongoDB client with prefix or panics on error

func NewClient

func NewClient() (*Client, error)

NewClient creates a new MongoDB client with environment-first configuration

func NewClientWithConfig

func NewClientWithConfig(config *Config) (*Client, error)

NewClientWithConfig creates a new MongoDB client with the provided configuration

func NewClientWithPrefix

func NewClientWithPrefix(prefix string) (*Client, error)

NewClientWithPrefix creates a new MongoDB client with a custom environment prefix

func Quick

func Quick(database ...string) (*Client, error)

Quick creates a quick MongoDB connection for simple use cases This is useful for scripts and simple applications that don't need advanced features

func (*Client) Close

func (c *Client) Close() error

Close gracefully closes the MongoDB connection

func (*Client) Collection

func (c *Client) Collection(name string) *Collection

Collection returns a MongoDB collection instance

func (*Client) CreateIndex

func (c *Client) CreateIndex(ctx context.Context, collectionName string, index IndexModel) (string, error)

CreateIndex creates an index on the specified collection

func (*Client) CreateIndexes

func (c *Client) CreateIndexes(ctx context.Context, collectionName string, indexes []IndexModel) ([]string, error)

CreateIndexes creates multiple indexes on the specified collection

func (*Client) Database

func (c *Client) Database(name ...string) *mongo.Database

Database returns the current database instance

func (*Client) DropDatabase

func (c *Client) DropDatabase(ctx context.Context) error

DropDatabase drops the current database

func (*Client) DropIndex

func (c *Client) DropIndex(ctx context.Context, collectionName string, indexName string) error

DropIndex drops an index from the specified collection

func (*Client) GetLastReconnectTime

func (c *Client) GetLastReconnectTime() time.Time

GetLastReconnectTime returns the time of the last reconnection

func (*Client) GetReconnectCount

func (c *Client) GetReconnectCount() int64

GetReconnectCount returns the number of reconnections performed

func (*Client) GetStats

func (c *Client) GetStats(ctx context.Context) (bson.M, error)

GetStats returns database statistics

func (*Client) HealthCheck

func (c *Client) HealthCheck() *HealthStatus

HealthCheck performs a manual health check and returns detailed status

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected returns whether the client is currently connected

func (*Client) ListCollections

func (c *Client) ListCollections(ctx context.Context, filter any, opts ...options.Lister[options.ListCollectionsOptions]) (*mongo.Cursor, error)

ListCollections lists all collections in the current database

func (*Client) ListDatabases

func (c *Client) ListDatabases(ctx context.Context, filter any, opts ...options.Lister[options.ListDatabasesOptions]) (mongo.ListDatabasesResult, error)

ListDatabases lists all databases

func (*Client) ListIndexes

func (c *Client) ListIndexes(ctx context.Context, collectionName string) (*mongo.Cursor, error)

ListIndexes lists all indexes for the specified collection

func (*Client) Ping

func (c *Client) Ping(ctx context.Context) error

Ping tests the connection to MongoDB

func (*Client) StartSession

func (c *Client) StartSession(opts ...options.Lister[options.SessionOptions]) (*mongo.Session, error)

StartSession starts a new session for transactions

func (*Client) WithTransaction

func (c *Client) WithTransaction(ctx context.Context, fn func(context.Context) (any, error), opts ...options.Lister[options.TransactionOptions]) (any, error)

WithTransaction executes a function within a transaction

type Collection

type Collection struct {
	// contains filtered or unexported fields
}

Collection wraps a MongoDB collection with enhanced functionality

func (*Collection) Aggregate

func (col *Collection) Aggregate(ctx context.Context, pipeline any, opts ...options.Lister[options.AggregateOptions]) (*mongo.Cursor, error)

Aggregate performs an aggregation operation

func (*Collection) CountDocuments

func (col *Collection) CountDocuments(ctx context.Context, filter any, opts ...options.Lister[options.CountOptions]) (int64, error)

CountDocuments counts documents in the collection

func (*Collection) CreateIndex

func (col *Collection) CreateIndex(ctx context.Context, index IndexModel) (string, error)

CreateIndex creates an index on this collection

func (*Collection) CreateIndexes

func (col *Collection) CreateIndexes(ctx context.Context, indexes []IndexModel) ([]string, error)

CreateIndexes creates multiple indexes on this collection

func (*Collection) DeleteMany

func (col *Collection) DeleteMany(ctx context.Context, filter any, opts ...options.Lister[options.DeleteManyOptions]) (*DeleteResult, error)

DeleteMany deletes multiple documents

func (*Collection) DeleteOne

func (col *Collection) DeleteOne(ctx context.Context, filter any, opts ...options.Lister[options.DeleteOneOptions]) (*DeleteResult, error)

DeleteOne deletes a single document

func (*Collection) Distinct

func (col *Collection) Distinct(ctx context.Context, fieldName string, filter any, opts ...options.Lister[options.DistinctOptions]) ([]any, error)

Distinct returns distinct values for a field

func (*Collection) Drop

func (col *Collection) Drop(ctx context.Context) error

Drop drops this collection

func (*Collection) DropIndex

func (col *Collection) DropIndex(ctx context.Context, indexName string) error

DropIndex drops an index from this collection

func (*Collection) EstimatedDocumentCount

func (col *Collection) EstimatedDocumentCount(ctx context.Context, opts ...options.Lister[options.EstimatedDocumentCountOptions]) (int64, error)

EstimatedDocumentCount returns an estimated count of documents

func (*Collection) Find

func (col *Collection) Find(ctx context.Context, filter any, opts ...options.Lister[options.FindOptions]) (*mongo.Cursor, error)

Find finds multiple documents

func (*Collection) FindByULID

func (col *Collection) FindByULID(ctx context.Context, ulid string) *mongo.SingleResult

FindByULID finds a document by its ULID

func (*Collection) FindOne

func (col *Collection) FindOne(ctx context.Context, filter any, opts ...options.Lister[options.FindOneOptions]) *mongo.SingleResult

FindOne finds a single document

func (*Collection) InsertMany

func (col *Collection) InsertMany(ctx context.Context, documents []any, opts ...options.Lister[options.InsertManyOptions]) (*InsertManyResult, error)

InsertMany inserts multiple documents with ULID generation

func (*Collection) InsertOne

func (col *Collection) InsertOne(ctx context.Context, document any, opts ...options.Lister[options.InsertOneOptions]) (*InsertOneResult, error)

InsertOne inserts a single document with ULID generation

func (*Collection) ListIndexes

func (col *Collection) ListIndexes(ctx context.Context) (*mongo.Cursor, error)

ListIndexes lists all indexes for this collection

func (*Collection) Name

func (col *Collection) Name() string

Name returns the collection name

func (*Collection) ReplaceOne

func (col *Collection) ReplaceOne(ctx context.Context, filter any, replacement any, opts ...options.Lister[options.ReplaceOptions]) (*UpdateResult, error)

ReplaceOne replaces a single document

func (*Collection) UpdateMany

func (col *Collection) UpdateMany(ctx context.Context, filter any, update any, opts ...options.Lister[options.UpdateManyOptions]) (*UpdateResult, error)

UpdateMany updates multiple documents

func (*Collection) UpdateOne

func (col *Collection) UpdateOne(ctx context.Context, filter any, update any, opts ...options.Lister[options.UpdateOneOptions]) (*UpdateResult, error)

UpdateOne updates a single document

func (*Collection) Watch

func (col *Collection) Watch(ctx context.Context, pipeline any, opts ...options.Lister[options.ChangeStreamOptions]) (*mongo.ChangeStream, error)

Watch creates a change stream for this collection

type Config

type Config struct {
	// Connection settings
	Host         string `env:"MONGODB_HOST,default=localhost"`
	Port         int    `env:"MONGODB_PORT,default=27017"`
	Username     string `env:"MONGODB_USERNAME"`
	Password     string `env:"MONGODB_PASSWORD"`
	Database     string `env:"MONGODB_DATABASE,default=app"`
	AuthDatabase string `env:"MONGODB_AUTH_DATABASE,default=admin"`
	ReplicaSet   string `env:"MONGODB_REPLICA_SET"`

	// Connection pool settings
	MaxPoolSize     uint64        `env:"MONGODB_MAX_POOL_SIZE,default=100"`
	MinPoolSize     uint64        `env:"MONGODB_MIN_POOL_SIZE,default=5"`
	MaxIdleTime     time.Duration `env:"MONGODB_MAX_IDLE_TIME,default=5m"`
	MaxConnIdleTime time.Duration `env:"MONGODB_MAX_CONN_IDLE_TIME,default=10m"`

	// Timeout settings
	ConnectTimeout      time.Duration `env:"MONGODB_CONNECT_TIMEOUT,default=10s"`
	ServerSelectTimeout time.Duration `env:"MONGODB_SERVER_SELECT_TIMEOUT,default=5s"`
	SocketTimeout       time.Duration `env:"MONGODB_SOCKET_TIMEOUT,default=10s"`

	// Reconnection settings
	ReconnectEnabled     bool          `env:"MONGODB_RECONNECT_ENABLED,default=true"`
	ReconnectDelay       time.Duration `env:"MONGODB_RECONNECT_DELAY,default=5s"`
	MaxReconnectDelay    time.Duration `env:"MONGODB_MAX_RECONNECT_DELAY,default=1m"`
	ReconnectBackoff     float64       `env:"MONGODB_RECONNECT_BACKOFF,default=2.0"`
	MaxReconnectAttempts int           `env:"MONGODB_MAX_RECONNECT_ATTEMPTS,default=10"`

	// Health check settings
	HealthCheckEnabled  bool          `env:"MONGODB_HEALTH_CHECK_ENABLED,default=true"`
	HealthCheckInterval time.Duration `env:"MONGODB_HEALTH_CHECK_INTERVAL,default=30s"`

	// Performance settings
	CompressionEnabled   bool   `env:"MONGODB_COMPRESSION_ENABLED,default=true"`
	CompressionAlgorithm string `env:"MONGODB_COMPRESSION_ALGORITHM,default=snappy"`
	ReadPreference       string `env:"MONGODB_READ_PREFERENCE,default=primary"`
	WriteConcern         string `env:"MONGODB_WRITE_CONCERN,default=majority"`
	ReadConcern          string `env:"MONGODB_READ_CONCERN,default=local"`

	// Application settings
	AppName        string `env:"MONGODB_APP_NAME,default=go-mongodb-app"`
	ConnectionName string `env:"MONGODB_CONNECTION_NAME"`

	// ID Generation settings
	IDMode IDMode `env:"MONGODB_ID_MODE,default=ulid"`

	// Logging
	LogLevel  string `env:"MONGODB_LOG_LEVEL,default=info"`
	LogFormat string `env:"MONGODB_LOG_FORMAT,default=json"`
}

Config holds MongoDB connection configuration

func LoadConfig

func LoadConfig() (*Config, error)

LoadConfig loads MongoDB configuration from environment variables

func LoadConfigWithPrefix

func LoadConfigWithPrefix(prefix string) (*Config, error)

LoadConfigWithPrefix loads MongoDB configuration with a custom environment prefix

func (*Config) BuildConnectionURI

func (c *Config) BuildConnectionURI() string

BuildConnectionURI constructs a MongoDB connection URI from configuration components

type D

type D = bson.D

D is an alias for bson.D (ordered document)

type DeleteResult

type DeleteResult struct {
	DeletedCount int64 `json:"deleted_count" bson:"deleted_count"`
}

DeleteResult represents the result of a delete operation

type E

type E = bson.E

E is an alias for bson.E (element)

type HealthStatus

type HealthStatus struct {
	IsHealthy bool          `json:"is_healthy"`
	Error     string        `json:"error,omitempty"`
	Latency   time.Duration `json:"latency"`
	CheckedAt time.Time     `json:"checked_at"`
}

HealthStatus represents the health status of a MongoDB connection

type IDMode

type IDMode string

IDMode defines the ID generation strategy for documents

const (
	// IDModeULID generates ULID strings as document IDs (default)
	IDModeULID IDMode = "ulid"
	// IDModeObjectID generates MongoDB ObjectIDs as document IDs
	IDModeObjectID IDMode = "objectid"
	// IDModeCustom allows users to provide their own _id fields
	IDModeCustom IDMode = "custom"
)

type IndexModel

type IndexModel struct {
	Keys    bson.D
	Options *options.IndexOptionsBuilder
}

IndexModel represents a MongoDB index

func IndexAsc

func IndexAsc(fields ...string) IndexModel

IndexAsc creates an ascending index model

func IndexDesc

func IndexDesc(fields ...string) IndexModel

IndexDesc creates a descending index model

func IndexText

func IndexText(fields ...string) IndexModel

IndexText creates a text index model

func IndexUnique

func IndexUnique(fields ...string) IndexModel

IndexUnique creates a unique index model

type InsertManyResult

type InsertManyResult struct {
	InsertedIDs   []string  `json:"inserted_ids" bson:"inserted_ids"` // ULIDs used directly as _ids
	InsertedCount int64     `json:"inserted_count" bson:"inserted_count"`
	GeneratedAt   time.Time `json:"generated_at" bson:"generated_at"`
}

InsertManyResult represents the result of a bulk insert operation

type InsertOneResult

type InsertOneResult struct {
	InsertedID  string    `json:"inserted_id" bson:"_id"` // ULID used directly as _id
	GeneratedAt time.Time `json:"generated_at" bson:"generated_at"`
}

InsertOneResult represents the result of an insert operation

type M

type M = bson.M

M is an alias for bson.M (map)

type QueryOptions

type QueryOptions struct {
	Sort       bson.D
	Limit      *int64
	Skip       *int64
	Projection bson.D
	Timeout    time.Duration
}

QueryOptions provides options for query operations

type ShutdownConfig

type ShutdownConfig struct {
	Timeout          time.Duration
	GracePeriod      time.Duration
	ForceKillTimeout time.Duration
}

ShutdownConfig holds configuration for graceful shutdown

type ShutdownManager

type ShutdownManager struct {
	// contains filtered or unexported fields
}

ShutdownManager manages graceful shutdown of MongoDB connections

func NewShutdownManager

func NewShutdownManager(config *ShutdownConfig) *ShutdownManager

NewShutdownManager creates a new shutdown manager

func NewShutdownManagerWithConfig

func NewShutdownManagerWithConfig(config *Config) *ShutdownManager

NewShutdownManagerWithConfig creates a shutdown manager with configuration

func (*ShutdownManager) Clear

func (sm *ShutdownManager) Clear()

Clear removes all registered clients

func (*ShutdownManager) Context

func (sm *ShutdownManager) Context() context.Context

Context returns the shutdown manager's context for background workers

func (*ShutdownManager) ForceShutdown

func (sm *ShutdownManager) ForceShutdown()

ForceShutdown immediately shuts down all clients without waiting

func (*ShutdownManager) GetClientCount

func (sm *ShutdownManager) GetClientCount() int

GetClientCount returns the number of registered clients

func (*ShutdownManager) GetTimeout

func (sm *ShutdownManager) GetTimeout() time.Duration

GetTimeout returns the current shutdown timeout

func (*ShutdownManager) Register

func (sm *ShutdownManager) Register(clients ...*Client)

Register registers MongoDB clients for graceful shutdown

func (*ShutdownManager) RegisterResources

func (sm *ShutdownManager) RegisterResources(resources ...Shutdownable)

RegisterResources registers shutdownable resources for graceful shutdown

func (*ShutdownManager) SetTimeout

func (sm *ShutdownManager) SetTimeout(timeout time.Duration)

SetTimeout updates the shutdown timeout

func (*ShutdownManager) SetupSignalHandler

func (sm *ShutdownManager) SetupSignalHandler()

SetupSignalHandler sets up signal handlers for graceful shutdown

func (*ShutdownManager) Wait

func (sm *ShutdownManager) Wait()

Wait blocks until a shutdown signal is received and performs graceful shutdown

type Shutdownable

type Shutdownable interface {
	Close() error
}

Shutdownable interface for resources that can be gracefully shut down

type TransactionOptions

type TransactionOptions struct {
	ReadConcern    *readconcern.ReadConcern
	WriteConcern   *writeconcern.WriteConcern
	ReadPreference *readpref.ReadPref
	MaxCommitTime  *time.Duration
}

TransactionOptions provides options for transactions

type UpdateResult

type UpdateResult struct {
	MatchedCount  int64  `json:"matched_count" bson:"matched_count"`
	ModifiedCount int64  `json:"modified_count" bson:"modified_count"`
	UpsertedID    string `json:"upserted_id,omitempty" bson:"upserted_id,omitempty"` // ULID string
	UpsertedCount int64  `json:"upserted_count" bson:"upserted_count"`
}

UpdateResult represents the result of an update operation

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL