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
- func Ascending(fields ...string) bson.D
- func ByField(field string, value any) bson.M
- func ByFields(fields bson.M) bson.M
- func ByID(id any) bson.M
- func ByULID(ulid string) bson.M
- func Descending(fields ...string) bson.D
- func EnhanceDocument(doc any) bson.M
- func GenerateULID() string
- func GenerateULIDFromTime(t time.Time) string
- func Group(id any, fields bson.M) bson.M
- func Inc(fields bson.M) bson.M
- func IsDuplicateKeyError(err error) bool
- func IsNetworkError(err error) bool
- func IsTimeoutError(err error) bool
- func Limit(n int64) bson.M
- func Lookup(from, localField, foreignField, as string) bson.M
- func Match(filter bson.M) bson.M
- func NewULID() string
- func Ping(ctx ...context.Context) error
- func Project(fields bson.M) bson.M
- func Pull(field string, value any) bson.M
- func Push(field string, value any) bson.M
- func Set(fields bson.M) bson.M
- func Skip(n int64) bson.M
- func Sort(fields bson.D) bson.M
- func Unset(fields ...string) bson.M
- type A
- type Client
- func Connect() (*Client, error)
- func ConnectWithConfig(config *Config) (*Client, error)
- func ConnectWithPrefix(prefix string) (*Client, error)
- func MustConnect() *Client
- func MustConnectWithPrefix(prefix string) *Client
- func NewClient() (*Client, error)
- func NewClientWithConfig(config *Config) (*Client, error)
- func NewClientWithPrefix(prefix string) (*Client, error)
- func Quick(database ...string) (*Client, error)
- func (c *Client) Close() error
- func (c *Client) Collection(name string) *Collection
- func (c *Client) CreateIndex(ctx context.Context, collectionName string, index IndexModel) (string, error)
- func (c *Client) CreateIndexes(ctx context.Context, collectionName string, indexes []IndexModel) ([]string, error)
- func (c *Client) Database(name ...string) *mongo.Database
- func (c *Client) DropDatabase(ctx context.Context) error
- func (c *Client) DropIndex(ctx context.Context, collectionName string, indexName string) error
- func (c *Client) GetLastReconnectTime() time.Time
- func (c *Client) GetReconnectCount() int64
- func (c *Client) GetStats(ctx context.Context) (bson.M, error)
- func (c *Client) HealthCheck() *HealthStatus
- func (c *Client) IsConnected() bool
- func (c *Client) ListCollections(ctx context.Context, filter any, ...) (*mongo.Cursor, error)
- func (c *Client) ListDatabases(ctx context.Context, filter any, ...) (mongo.ListDatabasesResult, error)
- func (c *Client) ListIndexes(ctx context.Context, collectionName string) (*mongo.Cursor, error)
- func (c *Client) Ping(ctx context.Context) error
- func (c *Client) StartSession(opts ...options.Lister[options.SessionOptions]) (*mongo.Session, error)
- func (c *Client) WithTransaction(ctx context.Context, fn func(context.Context) (any, error), ...) (any, error)
- type Collection
- func (col *Collection) Aggregate(ctx context.Context, pipeline any, ...) (*mongo.Cursor, error)
- func (col *Collection) CountDocuments(ctx context.Context, filter any, opts ...options.Lister[options.CountOptions]) (int64, error)
- func (col *Collection) CreateIndex(ctx context.Context, index IndexModel) (string, error)
- func (col *Collection) CreateIndexes(ctx context.Context, indexes []IndexModel) ([]string, error)
- func (col *Collection) DeleteMany(ctx context.Context, filter any, ...) (*DeleteResult, error)
- func (col *Collection) DeleteOne(ctx context.Context, filter any, ...) (*DeleteResult, error)
- func (col *Collection) Distinct(ctx context.Context, fieldName string, filter any, ...) ([]any, error)
- func (col *Collection) Drop(ctx context.Context) error
- func (col *Collection) DropIndex(ctx context.Context, indexName string) error
- func (col *Collection) EstimatedDocumentCount(ctx context.Context, ...) (int64, error)
- func (col *Collection) Find(ctx context.Context, filter any, opts ...options.Lister[options.FindOptions]) (*mongo.Cursor, error)
- func (col *Collection) FindByULID(ctx context.Context, ulid string) *mongo.SingleResult
- func (col *Collection) FindOne(ctx context.Context, filter any, ...) *mongo.SingleResult
- func (col *Collection) InsertMany(ctx context.Context, documents []any, ...) (*InsertManyResult, error)
- func (col *Collection) InsertOne(ctx context.Context, document any, ...) (*InsertOneResult, error)
- func (col *Collection) ListIndexes(ctx context.Context) (*mongo.Cursor, error)
- func (col *Collection) Name() string
- func (col *Collection) ReplaceOne(ctx context.Context, filter any, replacement any, ...) (*UpdateResult, error)
- func (col *Collection) UpdateMany(ctx context.Context, filter any, update any, ...) (*UpdateResult, error)
- func (col *Collection) UpdateOne(ctx context.Context, filter any, update any, ...) (*UpdateResult, error)
- func (col *Collection) Watch(ctx context.Context, pipeline any, ...) (*mongo.ChangeStream, error)
- type Config
- type D
- type DeleteResult
- type E
- type HealthStatus
- type IDMode
- type IndexModel
- type InsertManyResult
- type InsertOneResult
- type M
- type QueryOptions
- type ShutdownConfig
- type ShutdownManager
- func (sm *ShutdownManager) Clear()
- func (sm *ShutdownManager) Context() context.Context
- func (sm *ShutdownManager) ForceShutdown()
- func (sm *ShutdownManager) GetClientCount() int
- func (sm *ShutdownManager) GetTimeout() time.Duration
- func (sm *ShutdownManager) Register(clients ...*Client)
- func (sm *ShutdownManager) RegisterResources(resources ...Shutdownable)
- func (sm *ShutdownManager) SetTimeout(timeout time.Duration)
- func (sm *ShutdownManager) SetupSignalHandler()
- func (sm *ShutdownManager) Wait()
- type Shutdownable
- type TransactionOptions
- type UpdateResult
Constants ¶
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
const Version = "1.0.0"
Version of the go-mongodb package
Variables ¶
This section is empty.
Functions ¶
func Descending ¶
Descending creates a descending sort order
func EnhanceDocument ¶
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 ¶
GenerateULIDFromTime generates a ULID with a specific timestamp
func IsDuplicateKeyError ¶
IsDuplicateKeyError checks if an error is a duplicate key error
func IsNetworkError ¶
IsNetworkError checks if an error is a network-related error
func IsTimeoutError ¶
IsTimeoutError checks if an error is a timeout error
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client represents a MongoDB client with auto-reconnection and environment-first configuration
func ConnectWithConfig ¶
ConnectWithConfig creates a new MongoDB client with the provided configuration
func ConnectWithPrefix ¶
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 ¶
MustConnectWithPrefix creates a new MongoDB client with prefix or panics on error
func NewClientWithConfig ¶
NewClientWithConfig creates a new MongoDB client with the provided configuration
func NewClientWithPrefix ¶
NewClientWithPrefix creates a new MongoDB client with a custom environment prefix
func Quick ¶
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) 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) DropDatabase ¶
DropDatabase drops the current database
func (*Client) GetLastReconnectTime ¶
GetLastReconnectTime returns the time of the last reconnection
func (*Client) GetReconnectCount ¶
GetReconnectCount returns the number of reconnections performed
func (*Client) HealthCheck ¶
func (c *Client) HealthCheck() *HealthStatus
HealthCheck performs a manual health check and returns detailed status
func (*Client) IsConnected ¶
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 ¶
ListIndexes lists all indexes for the specified collection
func (*Client) StartSession ¶
func (c *Client) StartSession(opts ...options.Lister[options.SessionOptions]) (*mongo.Session, error)
StartSession starts a new session for transactions
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 ¶
ListIndexes lists all indexes for this collection
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 ¶
LoadConfig loads MongoDB configuration from environment variables
func LoadConfigWithPrefix ¶
LoadConfigWithPrefix loads MongoDB configuration with a custom environment prefix
func (*Config) BuildConnectionURI ¶
BuildConnectionURI constructs a MongoDB connection URI from configuration components
type DeleteResult ¶
type DeleteResult struct {
DeletedCount int64 `json:"deleted_count" bson:"deleted_count"`
}
DeleteResult represents the result of a delete operation
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 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 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 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