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_HOSTS: MongoDB server hosts (default: localhost: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_DIRECT_CONNECTION: Enable direct connection mode (default: false)
- 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 Document(keyValuePairs ...any) bson.M
- 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 IsNotFoundError(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 Projection(specs ...ProjectionSpec) bson.D
- 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 SortAsc(field string) bson.D
- func SortDesc(field string) bson.D
- func SortMultiple(fields map[string]int) bson.D
- func SortMultipleOrdered(fieldOrderPairs ...any) bson.D
- func Unset(fields ...string) bson.M
- type A
- type AggregateResult
- 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(opts ...Option) (*Client, error)
- func NewClientFromEnv() (*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) *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) 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) Name() string
- func (c *Client) Ping(ctx context.Context) error
- func (c *Client) StartSession(opts ...options.Lister[options.SessionOptions]) (*mongo.Session, error)
- func (c *Client) Stats() *ClientStats
- func (c *Client) WithTransaction(ctx context.Context, fn func(context.Context) (any, error), ...) (any, error)
- type ClientStats
- type Collection
- func (col *Collection) Aggregate(ctx context.Context, pipeline any, ...) (*mongo.Cursor, error)
- func (col *Collection) AggregateWithPipeline(ctx context.Context, pipelineBuilder *pipeline.Builder, ...) (*AggregateResult, error)
- func (col *Collection) CountDocuments(ctx context.Context, filterBuilder *filter.Builder, ...) (int64, error)
- func (col *Collection) CreateIndex(ctx context.Context, model mongo.IndexModel, ...) (string, error)
- func (col *Collection) CreateIndexes(ctx context.Context, models []mongo.IndexModel, ...) ([]string, error)
- func (col *Collection) DeleteMany(ctx context.Context, filterBuilder *filter.Builder, ...) (*DeleteResult, error)
- func (col *Collection) DeleteOne(ctx context.Context, filterBuilder *filter.Builder, ...) (*DeleteResult, error)
- func (col *Collection) Distinct(ctx context.Context, fieldName string, filterBuilder *filter.Builder, ...) ([]any, error)
- func (col *Collection) DropIndex(ctx context.Context, name string, ...) error
- func (col *Collection) Find(ctx context.Context, filterBuilder *filter.Builder, ...) (*FindResult, error)
- func (col *Collection) FindAscending(ctx context.Context, filterBuilder *filter.Builder, field string) (*FindResult, error)
- func (col *Collection) FindByULID(ctx context.Context, ulid string) *FindOneResult
- func (col *Collection) FindDescending(ctx context.Context, filterBuilder *filter.Builder, field string) (*FindResult, error)
- func (col *Collection) FindOne(ctx context.Context, filterBuilder *filter.Builder, ...) *FindOneResult
- func (col *Collection) FindOneAscending(ctx context.Context, filterBuilder *filter.Builder, field string) *FindOneResult
- func (col *Collection) FindOneDescending(ctx context.Context, filterBuilder *filter.Builder, field string) *FindOneResult
- func (col *Collection) FindOneSorted(ctx context.Context, filterBuilder *filter.Builder, sort SortSpec) *FindOneResult
- func (col *Collection) FindOneWithOptions(ctx context.Context, filterBuilder *filter.Builder, queryOpts *QueryOptions) *FindOneResult
- func (col *Collection) FindSorted(ctx context.Context, filterBuilder *filter.Builder, sort SortSpec, ...) (*FindResult, error)
- func (col *Collection) FindWithLimit(ctx context.Context, filterBuilder *filter.Builder, limit int64) (*FindResult, error)
- func (col *Collection) FindWithOptions(ctx context.Context, filterBuilder *filter.Builder, queryOpts *QueryOptions) (*FindResult, error)
- func (col *Collection) FindWithProjection(ctx context.Context, filterBuilder *filter.Builder, projection bson.M) (*FindResult, error)
- func (col *Collection) FindWithProjectionFields(ctx context.Context, filterBuilder *filter.Builder, ...) (*FindResult, error)
- func (col *Collection) FindWithSkip(ctx context.Context, filterBuilder *filter.Builder, skip int64) (*FindResult, error)
- func (col *Collection) Indexes() mongo.IndexView
- 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, opts ...options.Lister[options.ListIndexesOptions]) (*mongo.Cursor, error)
- func (col *Collection) Name() string
- func (col *Collection) ReplaceOne(ctx context.Context, filterBuilder *filter.Builder, replacement any, ...) (*UpdateResult, error)
- func (col *Collection) UpdateMany(ctx context.Context, filterBuilder *filter.Builder, ...) (*UpdateResult, error)
- func (col *Collection) UpdateOne(ctx context.Context, filterBuilder *filter.Builder, ...) (*UpdateResult, error)
- func (col *Collection) UpsertByField(ctx context.Context, field string, value any, document any) (*UpdateResult, error)
- func (col *Collection) UpsertByFieldMap(ctx context.Context, field string, value any, fields map[string]any) (*UpdateResult, error)
- func (col *Collection) UpsertByFieldWithOptions(ctx context.Context, field string, value any, document any, ...) (*UpdateResult, error)
- func (col *Collection) Watch(ctx context.Context, pipeline any, ...) (*mongo.ChangeStream, error)
- type Config
- type D
- type Database
- func (db *Database) Client() *Client
- func (db *Database) Collection(name string) *Collection
- func (db *Database) CreateCollection(ctx context.Context, name string) error
- func (db *Database) Drop(ctx context.Context) error
- func (db *Database) ListCollectionNames(ctx context.Context) ([]string, error)
- func (db *Database) Name() string
- func (db *Database) RunCommand(ctx context.Context, runCommand any) *mongo.SingleResult
- type DeleteResult
- type E
- type FindOneResult
- type FindResult
- type HealthStatus
- type IDMode
- type IndexModel
- type InsertManyResult
- type InsertOneResult
- type Logger
- type M
- type NopLogger
- type Option
- func FromEnv() Option
- func FromEnvWithPrefix(prefix string) Option
- func WithAppName(name string) Option
- func WithAuthSource(source string) Option
- func WithConnectTimeout(duration time.Duration) Option
- func WithConnectionName(name string) Option
- func WithCredentials(username, password string) Option
- func WithDatabase(name string) Option
- func WithDirectConnection(enabled bool) Option
- func WithEnvPrefix(prefix string) Option
- func WithHosts(hosts ...string) Option
- func WithLogger(logger Logger) Option
- func WithMaxIdleTime(duration time.Duration) Option
- func WithMaxPoolSize(size int) Option
- func WithMinPoolSize(size int) Option
- func WithReadPreference(pref ReadPreference) Option
- func WithReplicaSet(name string) Option
- func WithServerSelectionTimeout(duration time.Duration) Option
- func WithTLS(enabled bool) Option
- func WithTLSConfig(config *tls.Config) Option
- func WithTimeout(duration time.Duration) Option
- func WithWriteConcern(concern WriteConcern) Option
- type ProjectionSpec
- type QueryOptions
- type ReadPreference
- 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 SortSpec
- type TransactionOptions
- type UpdateResult
- type UpsertOptions
- type WriteConcern
Constants ¶
const ( EnvMongoDBHosts = "MONGODB_HOSTS" 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" EnvMongoDBDirectConnection = "MONGODB_DIRECT_CONNECTION" 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 Document ¶ added in v1.4.0
Document creates a BSON document from key-value pairs Usage: Document("name", "John", "age", 30)
func EnhanceDocument ¶
EnhanceDocument adds ULID 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 IsNotFoundError ¶ added in v1.1.0
IsNotFoundError checks if an error indicates that a document, collection, or database was not found
func IsTimeoutError ¶
IsTimeoutError checks if an error is a timeout error
func Projection ¶ added in v1.4.0
func Projection(specs ...ProjectionSpec) bson.D
Projection creates a projection document with included/excluded fields Usage: Projection(Include("name", "email"), Exclude("_id"))
func SortMultiple ¶ added in v1.4.0
SortMultiple creates a sort specification from a map of field:order pairs Note: Go maps are unordered, so use this only when sort order doesn't matter For ordered sorting, use SortMultipleOrdered or bson.D directly
func SortMultipleOrdered ¶ added in v1.4.0
SortMultipleOrdered creates an ordered sort specification from field-order pairs Usage: SortMultipleOrdered("created_at", -1, "name", 1)
Types ¶
type AggregateResult ¶ added in v1.1.0
type AggregateResult struct {
// contains filtered or unexported fields
}
AggregateResult wraps mongo.Cursor for aggregation operations
func (*AggregateResult) All ¶ added in v1.1.0
func (r *AggregateResult) All(ctx context.Context, results any) error
func (*AggregateResult) Close ¶ added in v1.1.0
func (r *AggregateResult) Close(ctx context.Context) error
func (*AggregateResult) Decode ¶ added in v1.1.0
func (r *AggregateResult) Decode(v any) error
func (*AggregateResult) Err ¶ added in v1.1.0
func (r *AggregateResult) Err() error
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 NewClient ¶
NewClient creates a new MongoDB client using functional options pattern. This is the primary constructor for the go-mongodb client.
Example usage:
client, err := NewClient(
WithDatabase("myapp"),
WithAppName("my-application"),
WithMaxPoolSize(50),
)
func NewClientFromEnv ¶ added in v1.1.0
NewClientFromEnv creates a new MongoDB client using environment variables. This is a convenience constructor that loads configuration from environment.
Supported environment variables:
MONGODB_HOSTS, MONGODB_USERNAME, MONGODB_PASSWORD, MONGODB_DATABASE, MONGODB_AUTH_DATABASE, etc.
func NewClientWithConfig ¶
NewClientWithConfig creates a new MongoDB client with the provided configuration
func NewClientWithPrefix ¶
NewClientWithPrefix creates a new MongoDB client using environment variables with a custom prefix
Example: If prefix is "APP", it will look for APP_MONGODB_HOSTS, APP_MONGODB_USERNAME, etc.
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) Database ¶
Database returns a database handle for the specified name using the modern API
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) 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) Name ¶ added in v1.1.0
Name returns the connection name for this client instance This is the local identifier used for application logging and metrics
func (*Client) StartSession ¶
func (c *Client) StartSession(opts ...options.Lister[options.SessionOptions]) (*mongo.Session, error)
StartSession starts a new session for transactions
func (*Client) Stats ¶ added in v1.1.0
func (c *Client) Stats() *ClientStats
Stats returns current client statistics and metrics
type ClientStats ¶ added in v1.1.0
type ClientStats struct {
// Connection pool statistics
ActiveConnections int `json:"active_connections"`
IdleConnections int `json:"idle_connections"`
TotalConnections int `json:"total_connections"`
// Operation statistics
OperationsExecuted int64 `json:"operations_executed"`
OperationsFailed int64 `json:"operations_failed"`
// Reconnection statistics
ReconnectAttempts int64 `json:"reconnect_attempts"`
LastReconnectTime *time.Time `json:"last_reconnect_time,omitempty"`
// Server information
ServerVersion string `json:"server_version"`
ReplicaSetName string `json:"replica_set_name,omitempty"`
IsMaster bool `json:"is_master"`
}
ClientStats represents internal client metrics and statistics
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) AggregateWithPipeline ¶ added in v1.3.1
func (col *Collection) AggregateWithPipeline(ctx context.Context, pipelineBuilder *pipeline.Builder, opts ...options.Lister[options.AggregateOptions]) (*AggregateResult, error)
AggregateWithPipeline performs an aggregation operation using a pipeline builder
func (*Collection) CountDocuments ¶
func (col *Collection) CountDocuments(ctx context.Context, filterBuilder *filter.Builder, opts ...options.Lister[options.CountOptions]) (int64, error)
CountDocuments counts documents in the collection
func (*Collection) CreateIndex ¶
func (col *Collection) CreateIndex(ctx context.Context, model mongo.IndexModel, opts ...options.Lister[options.CreateIndexesOptions]) (string, error)
CreateIndex creates a single index
func (*Collection) CreateIndexes ¶
func (col *Collection) CreateIndexes(ctx context.Context, models []mongo.IndexModel, opts ...options.Lister[options.CreateIndexesOptions]) ([]string, error)
CreateIndexes creates multiple indexes
func (*Collection) DeleteMany ¶
func (col *Collection) DeleteMany(ctx context.Context, filterBuilder *filter.Builder, opts ...options.Lister[options.DeleteManyOptions]) (*DeleteResult, error)
DeleteMany deletes multiple documents
func (*Collection) DeleteOne ¶
func (col *Collection) DeleteOne(ctx context.Context, filterBuilder *filter.Builder, opts ...options.Lister[options.DeleteOneOptions]) (*DeleteResult, error)
DeleteOne deletes a single document
func (*Collection) Distinct ¶
func (col *Collection) Distinct(ctx context.Context, fieldName string, filterBuilder *filter.Builder, opts ...options.Lister[options.DistinctOptions]) ([]any, error)
Distinct returns distinct values for a field
func (*Collection) DropIndex ¶
func (col *Collection) DropIndex(ctx context.Context, name string, opts ...options.Lister[options.DropIndexesOptions]) error
DropIndex drops a single index
func (*Collection) Find ¶
func (col *Collection) Find(ctx context.Context, filterBuilder *filter.Builder, opts ...options.Lister[options.FindOptions]) (*FindResult, error)
Find finds multiple documents using a filter builder
func (*Collection) FindAscending ¶ added in v1.4.0
func (col *Collection) FindAscending(ctx context.Context, filterBuilder *filter.Builder, field string) (*FindResult, error)
FindAscending finds documents sorted by a field in ascending order
func (*Collection) FindByULID ¶
func (col *Collection) FindByULID(ctx context.Context, ulid string) *FindOneResult
FindByULID finds a document by its ULID
func (*Collection) FindDescending ¶ added in v1.4.0
func (col *Collection) FindDescending(ctx context.Context, filterBuilder *filter.Builder, field string) (*FindResult, error)
FindDescending finds documents sorted by a field in descending order
func (*Collection) FindOne ¶
func (col *Collection) FindOne(ctx context.Context, filterBuilder *filter.Builder, opts ...options.Lister[options.FindOneOptions]) *FindOneResult
FindOne finds a single document using a filter builder
func (*Collection) FindOneAscending ¶ added in v1.4.0
func (col *Collection) FindOneAscending(ctx context.Context, filterBuilder *filter.Builder, field string) *FindOneResult
FindOneAscending finds a single document sorted by a field in ascending order
func (*Collection) FindOneDescending ¶ added in v1.4.0
func (col *Collection) FindOneDescending(ctx context.Context, filterBuilder *filter.Builder, field string) *FindOneResult
FindOneDescending finds a single document sorted by a field in descending order
func (*Collection) FindOneSorted ¶ added in v1.3.1
func (col *Collection) FindOneSorted(ctx context.Context, filterBuilder *filter.Builder, sort SortSpec) *FindOneResult
FindOneSorted finds a single document with a sort order
func (*Collection) FindOneWithOptions ¶ added in v1.3.1
func (col *Collection) FindOneWithOptions(ctx context.Context, filterBuilder *filter.Builder, queryOpts *QueryOptions) *FindOneResult
FindOneWithOptions finds a single document with QueryOptions
func (*Collection) FindSorted ¶ added in v1.3.1
func (col *Collection) FindSorted(ctx context.Context, filterBuilder *filter.Builder, sort SortSpec, opts ...options.Lister[options.FindOptions]) (*FindResult, error)
FindSorted finds documents with a sort order
func (*Collection) FindWithLimit ¶ added in v1.3.1
func (col *Collection) FindWithLimit(ctx context.Context, filterBuilder *filter.Builder, limit int64) (*FindResult, error)
FindWithLimit finds documents with a limit
func (*Collection) FindWithOptions ¶ added in v1.3.1
func (col *Collection) FindWithOptions(ctx context.Context, filterBuilder *filter.Builder, queryOpts *QueryOptions) (*FindResult, error)
FindWithOptions finds documents with QueryOptions for convenient sorting, limiting, etc.
func (*Collection) FindWithProjection ¶ added in v1.3.1
func (col *Collection) FindWithProjection(ctx context.Context, filterBuilder *filter.Builder, projection bson.M) (*FindResult, error)
FindWithProjection finds documents with field projection
func (*Collection) FindWithProjectionFields ¶ added in v1.4.0
func (col *Collection) FindWithProjectionFields(ctx context.Context, filterBuilder *filter.Builder, includeFields, excludeFields []string) (*FindResult, error)
FindWithProjectionFields finds documents with specific field projections
func (*Collection) FindWithSkip ¶ added in v1.3.1
func (col *Collection) FindWithSkip(ctx context.Context, filterBuilder *filter.Builder, skip int64) (*FindResult, error)
FindWithSkip finds documents with a skip offset
func (*Collection) Indexes ¶ added in v1.1.0
func (col *Collection) Indexes() mongo.IndexView
Indexes returns the index operations for this collection
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, opts ...options.Lister[options.ListIndexesOptions]) (*mongo.Cursor, error)
ListIndexes returns a cursor for all indexes in the collection
func (*Collection) ReplaceOne ¶
func (col *Collection) ReplaceOne(ctx context.Context, filterBuilder *filter.Builder, replacement any, opts ...options.Lister[options.ReplaceOptions]) (*UpdateResult, error)
ReplaceOne replaces a single document
func (*Collection) UpdateMany ¶
func (col *Collection) UpdateMany(ctx context.Context, filterBuilder *filter.Builder, updateBuilder *update.Builder, opts ...options.Lister[options.UpdateManyOptions]) (*UpdateResult, error)
UpdateMany updates multiple documents
func (*Collection) UpdateOne ¶
func (col *Collection) UpdateOne(ctx context.Context, filterBuilder *filter.Builder, updateBuilder *update.Builder, opts ...options.Lister[options.UpdateOneOptions]) (*UpdateResult, error)
UpdateOne updates a single document
func (*Collection) UpsertByField ¶ added in v1.3.0
func (col *Collection) UpsertByField(ctx context.Context, field string, value any, document any) (*UpdateResult, error)
UpsertByField performs an atomic upsert based on a specific field match This is a convenience method that combines filter creation, update building, and upsert execution
func (*Collection) UpsertByFieldMap ¶ added in v1.3.0
func (col *Collection) UpsertByFieldMap(ctx context.Context, field string, value any, fields map[string]any) (*UpdateResult, error)
UpsertByFieldMap performs an atomic upsert based on a specific field match using a map for the document
func (*Collection) UpsertByFieldWithOptions ¶ added in v1.3.0
func (col *Collection) UpsertByFieldWithOptions(ctx context.Context, field string, value any, document any, upsertOpts *UpsertOptions) (*UpdateResult, error)
UpsertByFieldWithOptions performs an atomic upsert with additional configuration options
func (*Collection) Watch ¶
func (col *Collection) Watch(ctx context.Context, pipeline any, opts ...options.Lister[options.ChangeStreamOptions]) (*mongo.ChangeStream, error)
Watch returns a change stream for the collection
type Config ¶
type Config struct {
// Connection settings
Hosts string `env:"MONGODB_HOSTS,default=localhost: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"`
DirectConnection bool `env:"MONGODB_DIRECT_CONNECTION,default=false"`
// 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"`
Logger Logger // Pluggable logger interface, defaults to NopLogger if not provided
}
Config holds MongoDB connection configuration
func (*Config) BuildConnectionURI ¶
BuildConnectionURI constructs a MongoDB connection URI from configuration components
type Database ¶ added in v1.1.0
type Database struct {
// contains filtered or unexported fields
}
Database represents a MongoDB database with modern fluent API
func (*Database) Collection ¶ added in v1.1.0
func (db *Database) Collection(name string) *Collection
Collection returns a collection handle for the specified name
func (*Database) CreateCollection ¶ added in v1.1.0
CreateCollection creates a new collection with the specified name
func (*Database) ListCollectionNames ¶ added in v1.1.0
ListCollectionNames returns the names of all collections in the database
func (*Database) RunCommand ¶ added in v1.1.0
RunCommand executes a database command
type DeleteResult ¶
type DeleteResult struct {
DeletedCount int64 `json:"deleted_count" bson:"deleted_count"`
}
DeleteResult represents the result of a delete operation
type FindOneResult ¶ added in v1.1.0
type FindOneResult struct {
// contains filtered or unexported fields
}
FindOneResult wraps mongo.SingleResult with additional methods
func (*FindOneResult) Decode ¶ added in v1.1.0
func (r *FindOneResult) Decode(v any) error
Methods for FindOneResult
func (*FindOneResult) Err ¶ added in v1.1.0
func (r *FindOneResult) Err() error
func (*FindOneResult) Raw ¶ added in v1.1.0
func (r *FindOneResult) Raw() ([]byte, error)
type FindResult ¶ added in v1.1.0
type FindResult struct {
// contains filtered or unexported fields
}
FindResult wraps mongo.Cursor with additional methods
func (*FindResult) All ¶ added in v1.1.0
func (r *FindResult) All(ctx context.Context, results any) error
func (*FindResult) Decode ¶ added in v1.1.0
func (r *FindResult) Decode(v any) error
func (*FindResult) Err ¶ added in v1.1.0
func (r *FindResult) Err() error
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 Logger ¶ added in v1.2.2
type Logger interface {
// Info logs an informational message with optional structured fields
Info(msg string, fields ...any)
// Warn logs a warning message with optional structured fields
Warn(msg string, fields ...any)
// Error logs an error message with optional structured fields
Error(msg string, fields ...any)
// Debug logs a debug message with optional structured fields
Debug(msg string, fields ...any)
}
Logger defines the interface for pluggable logging in the MongoDB client. Users can implement this interface to integrate their preferred logging solution.
type NopLogger ¶ added in v1.2.2
type NopLogger struct{}
NopLogger is a no-operation logger that discards all log messages. This is used as the default logger when no logger is provided via WithLogger.
type Option ¶ added in v1.1.0
type Option func(*Config)
Option represents a functional option for configuring the MongoDB client
func FromEnv ¶ added in v1.1.0
func FromEnv() Option
FromEnv returns an option that loads configuration from environment variables
func FromEnvWithPrefix ¶ added in v1.1.0
FromEnvWithPrefix returns an option that loads configuration from environment variables with a custom prefix
func WithAppName ¶ added in v1.1.0
WithAppName sets the application name for connection metadata
func WithAuthSource ¶ added in v1.1.0
WithAuthSource sets the authentication database
func WithConnectTimeout ¶ added in v1.1.0
WithConnectTimeout sets the connection timeout
func WithConnectionName ¶ added in v1.1.0
WithConnectionName sets a local identifier for this client instance This is used for application-level logging and metrics, not sent to MongoDB
func WithCredentials ¶ added in v1.1.0
WithCredentials sets the authentication credentials
func WithDatabase ¶ added in v1.1.0
WithDatabase sets the default database name
func WithDirectConnection ¶ added in v1.2.0
WithDirectConnection enables or disables direct connection mode When enabled, connects directly to a single MongoDB instance without replica set discovery Note: This only takes effect when connecting to a single host
func WithEnvPrefix ¶ added in v1.1.0
WithEnvPrefix sets a custom prefix for environment variables
func WithLogger ¶ added in v1.2.2
WithLogger sets a custom logger implementation for the MongoDB client If not provided, the client will use a NopLogger that produces no output
func WithMaxIdleTime ¶ added in v1.1.0
WithMaxIdleTime sets the maximum time a connection can remain idle
func WithMaxPoolSize ¶ added in v1.1.0
WithMaxPoolSize sets the maximum number of connections in the pool
func WithMinPoolSize ¶ added in v1.1.0
WithMinPoolSize sets the minimum number of connections in the pool
func WithReadPreference ¶ added in v1.1.0
func WithReadPreference(pref ReadPreference) Option
WithReadPreference sets the read preference
func WithReplicaSet ¶ added in v1.1.0
WithReplicaSet sets the replica set name
func WithServerSelectionTimeout ¶ added in v1.1.0
WithServerSelectionTimeout sets the server selection timeout
func WithTLSConfig ¶ added in v1.1.0
WithTLSConfig sets custom TLS configuration
func WithTimeout ¶ added in v1.1.0
WithTimeout sets the default operation timeout
func WithWriteConcern ¶ added in v1.1.0
func WithWriteConcern(concern WriteConcern) Option
WithWriteConcern sets the write concern
type ProjectionSpec ¶ added in v1.4.0
ProjectionSpec represents field inclusion/exclusion in projections
func Exclude ¶ added in v1.4.0
func Exclude(fields ...string) ProjectionSpec
Exclude creates a projection spec that excludes the specified fields
func Include ¶ added in v1.4.0
func Include(fields ...string) ProjectionSpec
Include creates a projection spec that includes the specified fields
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 ReadPreference ¶ added in v1.1.0
type ReadPreference string
ReadPreference represents MongoDB read preference options
const ( Primary ReadPreference = "primary" PrimaryPreferred ReadPreference = "primaryPreferred" Secondary ReadPreference = "secondary" SecondaryPreferred ReadPreference = "secondaryPreferred" Nearest ReadPreference = "nearest" )
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 SortSpec ¶ added in v1.4.0
type SortSpec interface{}
SortSpec represents a flexible sort specification that can be: - bson.D for ordered sorting - map[string]int for simple field:order mapping - mongodb.D (re-exported bson.D from mongodb.go)
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
type UpsertOptions ¶ added in v1.3.0
type UpsertOptions struct {
// OnlyInsert when true, ensures existing documents are never modified
// This is the default behavior when using $setOnInsert
OnlyInsert bool
}
UpsertOptions provides configuration for upsert operations
type WriteConcern ¶ added in v1.1.0
type WriteConcern string
WriteConcern represents MongoDB write concern options
const ( WCMajority WriteConcern = "majority" WCAcknowl WriteConcern = "acknowledged" WCUnacknowl WriteConcern = "unacknowledged" WCJournaled WriteConcern = "journaled" )
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
atomic-upsert
command
|
|
|
basic-client
command
|
|
|
bson-convenience-demo
command
|
|
|
direct-connection
command
|
|
|
env-config
command
|
|
|
id-modes
command
|
|
|
modern-api
command
|
|
|
modern-api-complete
command
|
|
|
query-options-demo
command
|
|
|
real-world-demo
command
|
|
|
reconnection-test
command
|
|
|
transactions
command
|
|
|
ulid-demo
command
|
|