mongodb

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 23 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
  • Pluggable Logging: Silent by default, integrate with any logging framework
  • High Performance: Optimized for throughput with efficient ULID generation
  • 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"
    "log"
    "github.com/cloudresty/go-mongodb"
    "github.com/cloudresty/go-mongodb/filter"
    "github.com/cloudresty/go-mongodb/update"
)

type User struct {
    Name   string `bson:"name" json:"name"`
    Email  string `bson:"email" json:"email"`
    Status string `bson:"status" json:"status"`
}

func main() {
    // Client - uses MONGODB_* environment variables
    client, err := mongodb.NewClient()
    if err != nil {
        panic(err)
    }
    defer client.Close()

    // Insert a document with auto-generated ULID ID using type-safe struct
    collection := client.Collection("users")
    user := User{
        Name:  "John Doe",
        Email: "john@example.com",
    }

    result, err := collection.InsertOne(context.Background(), user)
    if err != nil {
        log.Fatal(err)
    }

    // Find documents using type-safe filter
    var foundUser User
    err = collection.FindOne(context.Background(),
        filter.Eq("email", "john@example.com")).Decode(&foundUser)
    if err != nil {
        log.Fatal(err)
    }

    // Update documents using type-safe update builder
    _, err = collection.UpdateOne(context.Background(),
        filter.Eq("email", "john@example.com"),
        update.Set("status", "active"))
    if err != nil {
        log.Fatal(err)
    }
}

🔝 back to top

 

Environment Configuration

Set environment variables for your deployment:

export MONGODB_HOSTS=localhost: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
ID Generation 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

Pluggable logging framework, efficient ULID generation, and optimized for high-throughput scenarios.

🔝 back to top

 

Production Usage

package main

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

func main() {
    // Use custom environment prefix for multi-service deployments
    client, err := mongodb.NewClient(mongodb.FromEnvWithPrefix("PAYMENTS_"))
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Or configure with custom logger (silent by default)
    // client, err := mongodb.NewClient(
    //     mongodb.FromEnv(),
    //     mongodb.WithLogger(yourCustomLogger), // Implement mongodb.Logger interface
    // )

    // Health checks and monitoring - use Ping to verify connectivity
    if err := client.Ping(context.Background()); err != nil {
        log.Fatalf("Health check failed: MongoDB is not reachable: %v", err)
    }
    log.Println("Health check passed: MongoDB is reachable.")

    // For detailed metrics, get the stats
    stats := client.Stats()
    log.Printf("Client stats: %+v", stats)

    // Graceful shutdown with signal handling
    shutdownManager := mongodb.NewShutdownManager(&mongodb.ShutdownConfig{
        Timeout: 30 * time.Second,
    })
    shutdownManager.SetupSignalHandler()
    shutdownManager.Register(client)
    shutdownManager.Wait() // Blocks until SIGINT/SIGTERM
}

🔝 back to top

 

Requirements

  • Go 1.24+ (recommended)
  • MongoDB 8.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  |  Docker Hub

 

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

View Source
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

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 Document added in v1.4.0

func Document(keyValuePairs ...any) bson.M

Document creates a BSON document from key-value pairs Usage: Document("name", "John", "age", 30)

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 IsNotFoundError added in v1.1.0

func IsNotFoundError(err error) bool

IsNotFoundError checks if an error indicates that a document, collection, or database was not found

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 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 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 SortAsc added in v1.4.0

func SortAsc(field string) bson.D

SortAsc creates an ascending sort specification for a single field

func SortDesc added in v1.4.0

func SortDesc(field string) bson.D

SortDesc creates a descending sort specification for a single field

func SortMultiple added in v1.4.0

func SortMultiple(fields map[string]int) bson.D

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

func SortMultipleOrdered(fieldOrderPairs ...any) bson.D

SortMultipleOrdered creates an ordered sort specification from field-order pairs Usage: SortMultipleOrdered("created_at", -1, "name", 1)

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

func (*AggregateResult) Next added in v1.1.0

func (r *AggregateResult) Next(ctx context.Context) bool

Methods for AggregateResult

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(opts ...Option) (*Client, error)

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

func NewClientFromEnv() (*Client, error)

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

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

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) *Database

Database returns a database handle for the specified name using the modern API

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) 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) Name added in v1.1.0

func (c *Client) Name() string

Name returns the connection name for this client instance This is the local identifier used for application logging and metrics

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) Stats added in v1.1.0

func (c *Client) Stats() *ClientStats

Stats returns current client statistics and metrics

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 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) Name

func (col *Collection) Name() string

Name returns the collection name

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

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 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) Client added in v1.1.0

func (db *Database) Client() *Client

Client returns the client that this database belongs to

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

func (db *Database) CreateCollection(ctx context.Context, name string) error

CreateCollection creates a new collection with the specified name

func (*Database) Drop added in v1.1.0

func (db *Database) Drop(ctx context.Context) error

Drop removes the entire database

func (*Database) ListCollectionNames added in v1.1.0

func (db *Database) ListCollectionNames(ctx context.Context) ([]string, error)

ListCollectionNames returns the names of all collections in the database

func (*Database) Name added in v1.1.0

func (db *Database) Name() string

Name returns the database name

func (*Database) RunCommand added in v1.1.0

func (db *Database) RunCommand(ctx context.Context, runCommand any) *mongo.SingleResult

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 E

type E = bson.E

E is an alias for bson.E (element)

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) Close added in v1.1.0

func (r *FindResult) Close(ctx context.Context) 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

func (*FindResult) Next added in v1.1.0

func (r *FindResult) Next(ctx context.Context) bool

Methods for FindResult

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

type M = bson.M

M is an alias for bson.M (map)

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.

func (NopLogger) Debug added in v1.2.2

func (NopLogger) Debug(msg string, fields ...any)

Debug implements Logger.Debug by doing nothing

func (NopLogger) Error added in v1.2.2

func (NopLogger) Error(msg string, fields ...any)

Error implements Logger.Error by doing nothing

func (NopLogger) Info added in v1.2.2

func (NopLogger) Info(msg string, fields ...any)

Info implements Logger.Info by doing nothing

func (NopLogger) Warn added in v1.2.2

func (NopLogger) Warn(msg string, fields ...any)

Warn implements Logger.Warn by doing nothing

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

func FromEnvWithPrefix(prefix string) Option

FromEnvWithPrefix returns an option that loads configuration from environment variables with a custom prefix

func WithAppName added in v1.1.0

func WithAppName(name string) Option

WithAppName sets the application name for connection metadata

func WithAuthSource added in v1.1.0

func WithAuthSource(source string) Option

WithAuthSource sets the authentication database

func WithConnectTimeout added in v1.1.0

func WithConnectTimeout(duration time.Duration) Option

WithConnectTimeout sets the connection timeout

func WithConnectionName added in v1.1.0

func WithConnectionName(name string) Option

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

func WithCredentials(username, password string) Option

WithCredentials sets the authentication credentials

func WithDatabase added in v1.1.0

func WithDatabase(name string) Option

WithDatabase sets the default database name

func WithDirectConnection added in v1.2.0

func WithDirectConnection(enabled bool) Option

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

func WithEnvPrefix(prefix string) Option

WithEnvPrefix sets a custom prefix for environment variables

func WithHosts added in v1.1.0

func WithHosts(hosts ...string) Option

WithHosts sets the MongoDB host addresses

func WithLogger added in v1.2.2

func WithLogger(logger Logger) Option

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

func WithMaxIdleTime(duration time.Duration) Option

WithMaxIdleTime sets the maximum time a connection can remain idle

func WithMaxPoolSize added in v1.1.0

func WithMaxPoolSize(size int) Option

WithMaxPoolSize sets the maximum number of connections in the pool

func WithMinPoolSize added in v1.1.0

func WithMinPoolSize(size int) Option

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

func WithReplicaSet(name string) Option

WithReplicaSet sets the replica set name

func WithServerSelectionTimeout added in v1.1.0

func WithServerSelectionTimeout(duration time.Duration) Option

WithServerSelectionTimeout sets the server selection timeout

func WithTLS added in v1.1.0

func WithTLS(enabled bool) Option

WithTLS enables or disables TLS/SSL

func WithTLSConfig added in v1.1.0

func WithTLSConfig(config *tls.Config) Option

WithTLSConfig sets custom TLS configuration

func WithTimeout added in v1.1.0

func WithTimeout(duration time.Duration) Option

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

type ProjectionSpec bson.D

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

	// SkipTimestamps when true, disables automatic timestamp addition
	SkipTimestamps 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"
)

Jump to

Keyboard shortcuts

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