mongo

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2025 License: MIT Imports: 11 Imported by: 0

README

mongo-kit-go

A comprehensive, thread-safe MongoDB client library for Go with convenient methods for connection management and database operations.

Go Version License

Features

  • 🚀 Simple & Intuitive API - Clean, easy-to-use interface for MongoDB operations
  • 🔧 Functional Options Pattern - Flexible configuration with sensible defaults
  • 🔒 Thread-Safe - Safe for concurrent use across goroutines
  • Connection Pooling - Built-in connection pool management
  • 🎯 Generic CRUD Operations - Comprehensive set of database operations
  • 🔍 Query Builders - Fluent interface for building complex queries
  • 📊 Aggregation Support - Full support for MongoDB aggregation pipelines
  • 🔄 Transaction Support - Session management for multi-document transactions
  • ⏱️ Context Support - All operations support context for timeouts and cancellation
  • 🛡️ Error Handling - Rich error types with proper error wrapping
  • 🎨 Zero Dependencies - Only depends on official MongoDB driver

Installation

go get github.com/edaniel30/mongo-kit-go

Quick Start

package main

import (
    "context"
    "log"

    "github.com/edaniel30/mongo-kit-go"
    "go.mongodb.org/mongo-driver/bson"
)

type User struct {
    ID    mongo.ObjectID `bson:"_id,omitempty"`
    Name  string         `bson:"name"`
    Email string         `bson:"email"`
}

func main() {
    // Create client with default configuration
    client, err := mongo.New(
        mongo.DefaultConfig(),
        mongo.WithURI("mongodb://localhost:27017"),
        mongo.WithDatabase("myapp"),
    )
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close(context.Background())

    ctx := context.Background()

    // Insert a document
    user := User{Name: "John", Email: "john@example.com"}
    id, err := client.InsertOne(ctx, "users", user)
    if err != nil {
        log.Fatal(err)
    }

    // Find a document
    var found User
    err = client.FindOne(ctx, "users", bson.M{"email": "john@example.com"}, &found)
    if err != nil {
        log.Fatal(err)
    }
}

Configuration

Default Configuration
cfg := mongo.DefaultConfig()
// Returns:
// {
//     URI: "mongodb://localhost:27017",
//     Database: "default",
//     MaxPoolSize: 100,
//     MinPoolSize: 10,
//     ConnectTimeout: 10 * time.Second,
//     ServerSelectionTimeout: 5 * time.Second,
//     SocketTimeout: 10 * time.Second,
//     Timeout: 10 * time.Second,
//     RetryWrites: true,
//     RetryReads: true,
//     ReadPreference: "primary",
// }
Custom Configuration
client, err := mongo.New(
    mongo.DefaultConfig(),
    mongo.WithURI("mongodb://user:pass@host:port"),
    mongo.WithDatabase("production"),
    mongo.WithMaxPoolSize(200),
    mongo.WithMinPoolSize(20),
    mongo.WithTimeout(30 * time.Second),
    mongo.WithAppName("MyService"),
    mongo.WithReplicaSet("rs0"),
    mongo.WithReadPreference("secondaryPreferred"),
    mongo.WithRetryWrites(true),
    mongo.WithDebug(true),
)

Available Options

Option Description Default
WithURI(uri) MongoDB connection URI mongodb://localhost:27017
WithDatabase(name) Default database name default
WithMaxPoolSize(size) Maximum connection pool size 100
WithMinPoolSize(size) Minimum connection pool size 10
WithConnectTimeout(duration) Connection timeout 10s
WithServerSelectionTimeout(duration) Server selection timeout 5s
WithSocketTimeout(duration) Socket operation timeout 10s
WithTimeout(duration) Default operation timeout 10s
WithAppName(name) Application name for logs ""
WithReplicaSet(name) Replica set name ""
WithReadPreference(pref) Read preference mode primary
WithRetryWrites(bool) Enable retry writes true
WithRetryReads(bool) Enable retry reads true
WithDebug(bool) Enable debug logging false
WithDirectConnection(bool) Direct connection mode false

CRUD Operations

All operations use the database configured in mongo.New(). This keeps the API clean and simple.

Insert Operations
// Insert one document
id, err := client.InsertOne(ctx, "users", document)

// Insert many documents
ids, err := client.InsertMany(ctx, "users", []interface{}{doc1, doc2})
Find Operations
// Find one document
var user User
err := client.FindOne(ctx, "users", bson.M{"email": "test@example.com"}, &user)

// Find all matching documents
var users []User
err := client.Find(ctx, "users", bson.M{"age": bson.M{"$gte": 18}}, &users)

// Count documents
count, err := client.CountDocuments(ctx, "users", bson.M{"active": true})
Update Operations
// Update one document
result, err := client.UpdateOne(ctx, "users",
    bson.M{"email": "test@example.com"},
    bson.M{"$set": bson.M{"age": 30}})

// Update many documents
result, err := client.UpdateMany(ctx, "users",
    bson.M{"age": bson.M{"$lt": 18}},
    bson.M{"$set": bson.M{"minor": true}})

// Replace one document
result, err := client.ReplaceOne(ctx, "users", filter, newDocument)
Delete Operations
// Delete one document
count, err := client.DeleteOne(ctx, "users", bson.M{"email": "test@example.com"})

// Delete many documents
count, err := client.DeleteMany(ctx, "users", bson.M{"active": false})

Query Builder

Build complex queries with a fluent interface:

qb := mongo.NewQueryBuilder()
filter, opts := qb.
    Equals("category", "Electronics").
    GreaterThan("price", 100).
    In("brand", "Apple", "Samsung", "Sony").
    Regex("name", ".*phone.*", "i").
    Sort("price", false).  // descending
    Limit(10).
    Skip(20).
    Build()

var products []Product
err := client.Find(ctx, "db", "products", filter, &products, opts)
Query Builder Methods
  • Equals(key, value) - Equality filter
  • NotEquals(key, value) - Not equals filter
  • GreaterThan(key, value) - Greater than filter
  • GreaterThanOrEqual(key, value) - Greater than or equal filter
  • LessThan(key, value) - Less than filter
  • LessThanOrEqual(key, value) - Less than or equal filter
  • In(key, ...values) - In array filter
  • NotIn(key, ...values) - Not in array filter
  • Exists(key, bool) - Field exists filter
  • Regex(key, pattern, options) - Regex filter
  • And(...conditions) - AND logical operator
  • Or(...conditions) - OR logical operator
  • Limit(n) - Limit results
  • Skip(n) - Skip results
  • Sort(field, ascending) - Sort results

Update Builder

Build complex update operations:

ub := mongo.NewUpdateBuilder()
update := ub.
    Set("status", "active").
    Inc("views", 1).
    Push("tags", "featured").
    CurrentDate("updated_at").
    Build()

result, err := client.UpdateOne(ctx, "db", "posts", filter, update)
Update Builder Methods
  • Set(key, value) - Set field value
  • SetMultiple(map) - Set multiple fields
  • Unset(...keys) - Remove fields
  • Inc(key, value) - Increment value
  • Mul(key, value) - Multiply value
  • Min(key, value) - Update if less than current
  • Max(key, value) - Update if greater than current
  • Push(key, value) - Append to array
  • Pull(key, value) - Remove from array
  • AddToSet(key, value) - Add to array if not exists
  • Pop(key, first) - Remove first/last array element
  • CurrentDate(key) - Set to current date
  • Rename(old, new) - Rename field

Aggregation Pipeline

Build aggregation pipelines with a fluent interface:

ab := mongo.NewAggregationBuilder()
pipeline := ab.
    Match(bson.M{"status": "active"}).
    Group("$category", bson.M{
        "count": bson.M{"$sum": 1},
        "avgPrice": bson.M{"$avg": "$price"},
    }).
    Sort(bson.M{"count": -1}).
    Limit(10).
    Build()

var results []bson.M
err := client.Aggregate(ctx, "db", "products", pipeline, &results)
Aggregation Methods
  • Match(filter) - Filter documents
  • Group(id, fields) - Group documents
  • Sort(sort) - Sort documents
  • Limit(n) - Limit results
  • Skip(n) - Skip documents
  • Project(projection) - Select fields
  • Unwind(path) - Deconstruct arrays
  • Lookup(from, localField, foreignField, as) - Join collections
  • AddStage(stage) - Add custom stage

Advanced Operations

Distinct Values
categories, err := client.Distinct(ctx, "db", "products", "category", bson.M{})
FindOneAndUpdate
var updated User
err := client.FindOneAndUpdate(ctx, "db", "users", filter, update, &updated)
FindOneAndReplace
var replaced User
err := client.FindOneAndReplace(ctx, "db", "users", filter, newDoc, &replaced)
FindOneAndDelete
var deleted User
err := client.FindOneAndDelete(ctx, "db", "users", filter, &deleted)
Bulk Write
models := []mongo.WriteModel{
    mongo.NewInsertOneModel().SetDocument(doc1),
    mongo.NewUpdateOneModel().SetFilter(filter).SetUpdate(update),
    mongo.NewDeleteOneModel().SetFilter(filter),
}
result, err := client.BulkWrite(ctx, "db", "collection", models)

Index Management

// Create index
indexName, err := client.CreateIndex(ctx, "db", "users",
    bson.D{{Key: "email", Value: 1}})

// Drop index
err := client.DropIndex(ctx, "db", "users", "email_1")

// List indexes
indexes, err := client.ListIndexes(ctx, "db", "users")

Transaction Support

// Using session
err := client.UseSession(ctx, func(sessCtx mongo.SessionContext) error {
    err := sessCtx.StartTransaction()
    if err != nil {
        return err
    }

    // Perform operations
    _, err = client.InsertOne(sessCtx, "db", "users", user1)
    if err != nil {
        sessCtx.AbortTransaction(sessCtx)
        return err
    }

    _, err = client.InsertOne(sessCtx, "db", "users", user2)
    if err != nil {
        sessCtx.AbortTransaction(sessCtx)
        return err
    }

    return sessCtx.CommitTransaction(sessCtx)
})

Helper Functions

// ObjectID helpers
id := mongo.NewObjectID()
oid, err := mongo.ToObjectID("507f1f77bcf86cd799439011")
oids, err := mongo.ToObjectIDs([]string{"id1", "id2"})
valid := mongo.IsValidObjectID("507f1f77bcf86cd799439011")

// BSON helpers
doc := mongo.ToBSON(map[string]interface{}{"key": "value"})
docs := mongo.ToBSONArray([]map[string]interface{}{...})
merged := mongo.MergeBSON(doc1, doc2, doc3)

Error Handling

_, err := client.FindOne(ctx, "db", "users", filter, &user)
if err != nil {
    if errors.Is(err, mongo.ErrDocumentNotFound()) {
        // Handle not found
    } else if errors.Is(err, mongo.ErrClientClosed()) {
        // Handle closed client
    } else {
        // Handle other errors
    }
}

Connection Management

// Check connection status
if !client.IsClosed() {
    if client.IsConnected(ctx) {
        // Client is connected
    }
}

// Get configuration
config := client.GetConfig()

// List databases
dbs, err := client.ListDatabases(ctx, bson.M{})

// List collections
collections, err := client.ListCollections(ctx, "mydb")

// Close connection
err := client.Close(context.Background())

Examples

See the examples directory for complete working examples:

Design Philosophy

This library is designed for applications that use a single database. The database is configured once during client initialization, keeping your code clean and simple.

// Configure database once
client, _ := mongo.New(
    mongo.DefaultConfig(),
    mongo.WithDatabase("myapp"),  // ← Set once
)

// Use everywhere without repeating database name
client.InsertOne(ctx, "users", user)       // Clean ✓
client.Find(ctx, "posts", filter, &posts)   // Simple ✓

This design choice makes the API:

  • Cleaner - Less repetition
  • Simpler - Fewer parameters
  • Safer - Can't accidentally use wrong database
  • Perfect for - Most web applications, APIs, microservices

Best Practices

  1. Use Context: Always pass context with appropriate timeouts
  2. Defer Close: Always defer client.Close() after creating the client
  3. Error Handling: Check and handle errors appropriately
  4. Connection Pooling: Reuse the same client instance across your application
  5. Indexes: Create indexes for frequently queried fields
  6. Projections: Use projections to fetch only required fields
  7. Bulk Operations: Use bulk operations for multiple writes

Contributing

Contributions are welcome! Please read CONTRIBUTING.md for details.

License

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

Support

For issues, questions, or contributions, please open an issue on GitHub.

Documentation

Overview

Package mongo provides a MongoDB client wrapper with convenient methods for connection management and database operations.

Key features:

  • Functional options pattern for configuration
  • Thread-safe operations with connection pooling
  • Context support for all operations
  • Generic CRUD operations with dynamic queries
  • Graceful shutdown with proper cleanup

Basic usage:

client, err := mongo.New(
    mongo.DefaultConfig(),
    mongo.WithURI("mongodb://localhost:27017"),
    mongo.WithDatabase("myapp"),
)
if err != nil {
    panic(err)
}
defer client.Close(context.Background())

Index

Constants

This section is empty.

Variables

View Source
var (
	// WithURI sets the MongoDB connection URI
	WithURI = models.WithURI
	// WithDatabase sets the default database name
	WithDatabase = models.WithDatabase
	// WithMaxPoolSize sets the maximum connection pool size
	WithMaxPoolSize = models.WithMaxPoolSize
	// WithMinPoolSize sets the minimum connection pool size
	WithMinPoolSize = models.WithMinPoolSize
	// WithConnectTimeout sets the connection timeout
	WithConnectTimeout = models.WithConnectTimeout
	// WithServerSelectionTimeout sets the server selection timeout
	WithServerSelectionTimeout = models.WithServerSelectionTimeout
	// WithSocketTimeout sets the socket operation timeout
	WithSocketTimeout = models.WithSocketTimeout
	// WithTimeout sets the default operation timeout
	WithTimeout = models.WithTimeout
	// WithDebug enables or disables debug logging
	WithDebug = models.WithDebug
	// WithRetryWrites enables or disables automatic retry of write operations
	WithRetryWrites = models.WithRetryWrites
	// WithRetryReads enables or disables automatic retry of read operations
	WithRetryReads = models.WithRetryReads
	// WithAppName sets the application name for MongoDB logs
	WithAppName = models.WithAppName
	// WithDirectConnection sets whether to connect directly to a single host
	WithDirectConnection = models.WithDirectConnection
	// WithReplicaSet sets the replica set name
	WithReplicaSet = models.WithReplicaSet
	// WithReadPreference sets the read preference mode
	WithReadPreference = models.WithReadPreference
	// WithMaxConnIdleTime sets the maximum idle time for connections
	WithMaxConnIdleTime = models.WithMaxConnIdleTime
	// WithHeartbeatInterval sets the interval between server heartbeats
	WithHeartbeatInterval = models.WithHeartbeatInterval
)
View Source
var (
	// ErrInvalidConfig returns a configuration error with the given message
	ErrInvalidConfig = errors.ErrInvalidConfig
	// ErrConnectionFailed returns an error indicating connection failure
	ErrConnectionFailed = errors.ErrConnectionFailed
	// ErrClientClosed returns an error indicating the client is closed
	ErrClientClosed = errors.ErrClientClosed
	// ErrInvalidOperation returns an error indicating an invalid operation
	ErrInvalidOperation = errors.ErrInvalidOperation
	// ErrDatabaseNotFound returns an error indicating database was not found
	ErrDatabaseNotFound = errors.ErrDatabaseNotFound
	// ErrCollectionNotFound returns an error indicating collection was not found
	ErrCollectionNotFound = errors.ErrCollectionNotFound
	// NewOperationError creates a new operation error
	NewOperationError = errors.NewOperationError
)

Re-export custom error functions

View Source
var (
	// ToObjectID converts a string to MongoDB ObjectID
	ToObjectID = helpers.ToObjectID
	// ToObjectIDs converts multiple strings to MongoDB ObjectIDs
	ToObjectIDs = helpers.ToObjectIDs
	// IsValidObjectID checks if a string is a valid MongoDB ObjectID
	IsValidObjectID = helpers.IsValidObjectID
	// NewObjectID generates a new MongoDB ObjectID
	NewObjectID = helpers.NewObjectID
	// ToBSON converts a map to BSON document
	ToBSON = helpers.ToBSON
	// ToBSONArray converts a slice of maps to BSON array
	ToBSONArray = helpers.ToBSONArray
	// MergeBSON merges multiple BSON documents
	MergeBSON = helpers.MergeBSON
	// BSONToMap converts a BSON document to a map
	BSONToMap = helpers.BSONToMap
)

Re-export helper functions

View Source
var (
	// ErrNoDocuments is returned when a query that expects a document doesn't find one
	ErrNoDocuments = mongo.ErrNoDocuments
	// ErrNilDocument is returned when a nil document is passed to an insert operation
	ErrNilDocument = mongo.ErrNilDocument
	// ErrNilValue is returned when a nil value is passed where it's not allowed
	ErrNilValue = mongo.ErrNilValue
	// ErrEmptySlice is returned when an empty slice is passed where it's not allowed
	ErrEmptySlice = mongo.ErrEmptySlice
	// ErrUnacknowledgedWrite is returned when attempting to get results from an unacknowledged write
	ErrUnacknowledgedWrite = mongo.ErrUnacknowledgedWrite
	// ErrClientDisconnected is returned when an operation is attempted on a disconnected client
	ErrClientDisconnected = mongo.ErrClientDisconnected
	// ErrInvalidIndexValue is returned when an invalid index value is encountered
	ErrInvalidIndexValue = mongo.ErrInvalidIndexValue
	// ErrInvalidObjectID is returned when an invalid ObjectID hex string is provided
	ErrInvalidObjectID = primitive.ErrInvalidHex
)

Re-export MongoDB driver sentinel errors for use with errors.Is()

View Source
var (
	// IsDuplicateKeyError checks if an error is a duplicate key error (E11000)
	IsDuplicateKeyError = mongo.IsDuplicateKeyError
	// IsTimeout checks if an error is a timeout error
	IsTimeout = mongo.IsTimeout
	// IsNetworkError checks if an error is a network error
	IsNetworkError = mongo.IsNetworkError
)

Re-export MongoDB driver error helper functions

View Source
var (
	// Index creates a new IndexOptions instance for configuring index creation
	Index = options.Index
	// Find creates a new FindOptions instance for configuring find operations
	Find = options.Find
	// FindOne creates a new FindOneOptions instance for configuring findOne operations
	FindOne = options.FindOne
	// Update creates a new UpdateOptions instance for configuring update operations
	Update = options.Update
	// Replace creates a new ReplaceOptions instance for configuring replace operations
	Replace = options.Replace
	// Delete creates a new DeleteOptions instance for configuring delete operations
	Delete = options.Delete
	// InsertOne creates a new InsertOneOptions instance for configuring insertOne operations
	InsertOne = options.InsertOne
	// InsertMany creates a new InsertManyOptions instance for configuring insertMany operations
	InsertMany = options.InsertMany
	// CreateCollection creates a new CreateCollectionOptions instance for configuring collection creation
	CreateCollection = options.CreateCollection
	// Aggregate creates a new AggregateOptions instance for configuring aggregate operations
	Aggregate = options.Aggregate
	// Count creates a new CountOptions instance for configuring count operations
	Count = options.Count
	// Distinct creates a new DistinctOptions instance for configuring distinct operations
	Distinct = options.Distinct
	// FindOneAndUpdate creates a new FindOneAndUpdateOptions instance
	FindOneAndUpdate = options.FindOneAndUpdate
	// FindOneAndReplace creates a new FindOneAndReplaceOptions instance
	FindOneAndReplace = options.FindOneAndReplace
	// FindOneAndDelete creates a new FindOneAndDeleteOptions instance
	FindOneAndDelete = options.FindOneAndDelete
	// BulkWrite creates a new BulkWriteOptions instance for configuring bulk write operations
	BulkWrite = options.BulkWrite
)

Options constructors for convenience

View Source
var (
	// DefaultConfig returns a Config with sensible default values
	DefaultConfig = models.DefaultConfig
)

Functions

This section is empty.

Types

type A

type A = bson.A

A is a convenient alias for bson.A

type AggregateOptions

type AggregateOptions = options.AggregateOptions

AggregateOptions is a convenient alias for options.AggregateOptions

type AggregationBuilder

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

AggregationBuilder provides a fluent interface for building aggregation pipelines

func NewAggregationBuilder

func NewAggregationBuilder() *AggregationBuilder

NewAggregationBuilder creates a new AggregationBuilder instance

func (*AggregationBuilder) AddStage

func (ab *AggregationBuilder) AddStage(stage bson.D) *AggregationBuilder

AddStage adds a custom pipeline stage

func (*AggregationBuilder) Build

func (ab *AggregationBuilder) Build() []bson.D

Build returns the aggregation pipeline

func (*AggregationBuilder) Group

func (ab *AggregationBuilder) Group(id interface{}, fields bson.M) *AggregationBuilder

Group adds a $group stage

func (*AggregationBuilder) Limit

func (ab *AggregationBuilder) Limit(limit int64) *AggregationBuilder

Limit adds a $limit stage

func (*AggregationBuilder) Lookup

func (ab *AggregationBuilder) Lookup(from, localField, foreignField, as string) *AggregationBuilder

Lookup adds a $lookup stage for joins

func (*AggregationBuilder) Match

func (ab *AggregationBuilder) Match(filter interface{}) *AggregationBuilder

Match adds a $match stage

func (*AggregationBuilder) Project

func (ab *AggregationBuilder) Project(projection interface{}) *AggregationBuilder

Project adds a $project stage

func (*AggregationBuilder) Skip

Skip adds a $skip stage

func (*AggregationBuilder) Sort

func (ab *AggregationBuilder) Sort(sort interface{}) *AggregationBuilder

Sort adds a $sort stage

func (*AggregationBuilder) Unwind

func (ab *AggregationBuilder) Unwind(path string) *AggregationBuilder

Unwind adds an $unwind stage

type BulkWriteOptions

type BulkWriteOptions = options.BulkWriteOptions

BulkWriteOptions is a convenient alias for options.BulkWriteOptions

type Client

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

Client wraps MongoDB client with convenience methods It is safe for concurrent use across goroutines

func New

func New(cfg models.Config, opts ...models.Option) (*Client, error)

New creates a new MongoDB client with the given configuration Configuration uses the functional options pattern for flexibility

func (*Client) Aggregate

func (c *Client) Aggregate(ctx context.Context, collection string, pipeline any, results any, opts ...*options.AggregateOptions) error

Aggregate executes an aggregation pipeline and decodes the results.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to aggregate on
  • pipeline: Aggregation pipeline stages as a slice (e.g., []bson.M, mongo.Pipeline)
  • results: Pointer to a slice where aggregation results will be decoded (e.g., *[]bson.M, *[]User)
  • opts: Optional AggregateOptions for batch size, collation, etc.

Returns:

  • error: Returns error if operation fails or client is closed

Example:

pipeline := []bson.M{
    {"$match": bson.M{"status": "active"}},
    {"$group": bson.M{"_id": "$country", "count": bson.M{"$sum": 1}}},
    {"$sort": bson.M{"count": -1}},
}
var results []bson.M
err := client.Aggregate(ctx, "users", pipeline, &results)
if err != nil {
    log.Fatal(err)
}
for _, result := range results {
    fmt.Printf("Country: %s, Count: %d\n", result["_id"], result["count"])
}

func (*Client) BulkWrite

func (c *Client) BulkWrite(ctx context.Context, collection string, models []mongo.WriteModel, opts ...*options.BulkWriteOptions) (*mongo.BulkWriteResult, error)

BulkWrite executes multiple write operations (insert, update, delete) in a single batch. This is more efficient than executing operations individually when performing multiple writes.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to write to
  • models: Slice of write models (mongo.InsertOneModel, mongo.UpdateOneModel, mongo.DeleteOneModel, etc.)
  • opts: Optional BulkWriteOptions for ordered execution, bypass validation, etc.

Returns:

  • *mongo.BulkWriteResult: Contains InsertedCount, MatchedCount, ModifiedCount, DeletedCount, UpsertedCount, and UpsertedIDs
  • error: Returns error if operation fails or client is closed

Example:

models := []mongo.WriteModel{
    mongo.NewInsertOneModel().SetDocument(User{Name: "Alice", Email: "alice@example.com"}),
    mongo.NewUpdateOneModel().SetFilter(bson.M{"name": "Bob"}).SetUpdate(bson.M{"$set": bson.M{"status": "active"}}),
    mongo.NewDeleteOneModel().SetFilter(bson.M{"name": "Charlie"}),
}
result, err := client.BulkWrite(ctx, "users", models)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Inserted: %d, Modified: %d, Deleted: %d\n", result.InsertedCount, result.ModifiedCount, result.DeletedCount)

func (*Client) Close

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

Close closes the MongoDB client connection gracefully After calling Close, the client should not be used

func (*Client) CountDocuments

func (c *Client) CountDocuments(ctx context.Context, collection string, filter any, opts ...*options.CountOptions) (int64, error)

CountDocuments counts the number of documents matching the filter.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to count in
  • filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} to count all documents
  • opts: Optional CountOptions for limit, skip, collation, etc.

Returns:

  • int64: The number of documents matching the filter
  • error: Returns error if operation fails or client is closed

Example:

filter := bson.M{"status": "active"}
count, err := client.CountDocuments(ctx, "users", filter)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Found %d active users\n", count)

func (*Client) CreateCollection

func (c *Client) CreateCollection(ctx context.Context, collection string, opts ...*options.CreateCollectionOptions) error

CreateCollection explicitly creates a new collection in the default database. Note: MongoDB creates collections automatically on first insert, but this method is useful for creating collections with specific options like validation, capped collections, or time series.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to create
  • opts: Optional CreateCollectionOptions for validation, capped collections, time series, collation, etc.

Returns:

  • error: Returns error if collection already exists, operation fails, or client is closed

Example:

// Create a simple collection
err := client.CreateCollection(ctx, "users")

// Create a capped collection (fixed size, FIFO)
cappedOpts := options.CreateCollection().
    SetCapped(true).
    SetSizeInBytes(1048576). // 1MB
    SetMaxDocuments(1000)
err := client.CreateCollection(ctx, "logs", cappedOpts)

// Create collection with schema validation
validator := bson.M{
    "$jsonSchema": bson.M{
        "bsonType": "object",
        "required": []string{"name", "email"},
        "properties": bson.M{
            "name":  bson.M{"bsonType": "string"},
            "email": bson.M{"bsonType": "string"},
            "age":   bson.M{"bsonType": "int", "minimum": 0},
        },
    },
}
validatorOpts := options.CreateCollection().SetValidator(validator)
err := client.CreateCollection(ctx, "validated_users", validatorOpts)

func (*Client) CreateCollections

func (c *Client) CreateCollections(ctx context.Context, collections map[string]*options.CreateCollectionOptions) error

CreateCollections creates multiple collections in the default database in a single operation. This is useful for initializing a database schema with multiple collections at once.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collections: Map where keys are collection names and values are optional CreateCollectionOptions (can be nil)

Returns:

  • error: Returns error if any collection creation fails or client is closed

Note: If one collection fails to create, subsequent collections will not be attempted. Consider using error handling to manage partial failures if needed.

Example:

// Create multiple collections with different options
collections := map[string]*options.CreateCollectionOptions{
    "users":    nil, // Simple collection, no special options
    "products": nil,
    "logs": options.CreateCollection(). // Capped collection for logs
        SetCapped(true).
        SetSizeInBytes(5242880). // 5MB
        SetMaxDocuments(10000),
    "orders": options.CreateCollection(). // Collection with validation
        SetValidator(bson.M{
            "$jsonSchema": bson.M{
                "bsonType": "object",
                "required": []string{"user_id", "total"},
            },
        }),
}
err := client.CreateCollections(ctx, collections)
if err != nil {
    log.Fatal(err)
}
fmt.Println("All collections created successfully")

func (*Client) CreateIndex

func (c *Client) CreateIndex(ctx context.Context, collection string, keys any, opts ...*options.IndexOptions) (string, error)

CreateIndex creates a new index on the specified collection to improve query performance.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to create the index on
  • keys: Index keys specification (e.g., bson.M{"email": 1} for ascending, bson.M{"age": -1} for descending)
  • opts: Optional IndexOptions for unique, sparse, partial filters, TTL, etc.

Returns:

  • string: The name of the created index
  • error: Returns error if operation fails or client is closed

Example:

// Create unique index on email field
keys := bson.M{"email": 1}
opts := options.Index().SetUnique(true)
indexName, err := client.CreateIndex(ctx, "users", keys, opts)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Created index: %s\n", indexName)

// Create compound index on multiple fields
compoundKeys := bson.D{{"country", 1}, {"city", 1}, {"created_at", -1}}
indexName, err := client.CreateIndex(ctx, "users", compoundKeys)

func (*Client) CreateIndexes

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

CreateIndexes creates multiple indexes across different collections in a single operation. This is useful for setting up database indexes during initialization or migrations.

Parameters:

  • ctx: Context for cancellation and timeout control
  • indexes: Map where keys are collection names and values are slices of IndexModel to create

Returns:

  • map[string][]string: Map of collection names to slices of created index names
  • error: Returns error if any index creation fails or client is closed

Note: If one index fails to create, subsequent indexes will not be attempted.

Example:

indexes := map[string][]mongo.IndexModel{
    "users": {
        {
            Keys:    bson.M{"email": 1},
            Options: options.Index().SetUnique(true).SetName("unique_email"),
        },
        {
            Keys:    bson.D{{"country", 1}, {"city", 1}},
            Options: options.Index().SetName("location_idx"),
        },
    },
    "products": {
        {
            Keys:    bson.M{"sku": 1},
            Options: options.Index().SetUnique(true),
        },
        {
            Keys:    bson.M{"category": 1, "price": -1},
            Options: options.Index().SetName("category_price_idx"),
        },
    },
}
createdIndexes, err := client.CreateIndexes(ctx, indexes)
if err != nil {
    log.Fatal(err)
}
for collection, indexNames := range createdIndexes {
    fmt.Printf("Collection '%s': created %d indexes\n", collection, len(indexNames))
}

func (*Client) DeleteMany

func (c *Client) DeleteMany(ctx context.Context, collection string, filter any, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

DeleteMany deletes all documents matching the filter.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to delete from
  • filter: Query filter to match documents to delete. Can be bson.M, bson.D, or a struct. Use bson.M{} to delete all documents
  • opts: Optional DeleteOptions for collation, hint, etc.

Returns:

  • *mongo.DeleteResult: Contains DeletedCount with the number of documents deleted
  • error: Returns error if operation fails or client is closed

Example:

filter := bson.M{"status": "inactive", "last_login": bson.M{"$lt": time.Now().AddDate(0, -6, 0)}}
result, err := client.DeleteMany(ctx, "users", filter)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Deleted %d inactive user(s)\n", result.DeletedCount)

func (*Client) DeleteOne

func (c *Client) DeleteOne(ctx context.Context, collection string, filter any, opts ...*options.DeleteOptions) (*mongo.DeleteResult, error)

DeleteOne deletes a single document matching the filter.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to delete from
  • filter: Query filter to match the document to delete. Can be bson.M, bson.D, or a struct
  • opts: Optional DeleteOptions for collation, hint, etc.

Returns:

  • *mongo.DeleteResult: Contains DeletedCount with the number of documents deleted (0 or 1)
  • error: Returns error if operation fails or client is closed

Example:

filter := bson.M{"email": "user@example.com"}
result, err := client.DeleteOne(ctx, "users", filter)
if err != nil {
    log.Fatal(err)
}
if result.DeletedCount == 0 {
    fmt.Println("No document was deleted")
}

func (*Client) Distinct

func (c *Client) Distinct(ctx context.Context, collection string, fieldName string, filter any, opts ...*options.DistinctOptions) ([]any, error)

Distinct gets all unique values for a specified field across documents matching the filter.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to query
  • fieldName: The field name to get distinct values from (e.g., "country", "tags", "status")
  • filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} for all documents
  • opts: Optional DistinctOptions for collation, etc.

Returns:

  • []any: Slice containing the distinct values found for the field
  • error: Returns error if operation fails or client is closed

Example:

filter := bson.M{"status": "active"}
countries, err := client.Distinct(ctx, "users", "country", filter)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Active users are from %d different countries\n", len(countries))
for _, country := range countries {
    fmt.Println(country)
}

func (*Client) DropIndex

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

DropIndex removes an index from the specified collection.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to drop the index from
  • indexName: Name of the index to drop (can be obtained from ListIndexes or when creating the index)

Returns:

  • error: Returns error if operation fails, index doesn't exist, or client is closed

Example:

err := client.DropIndex(ctx, "users", "email_1")
if err != nil {
    log.Fatal(err)
}
fmt.Println("Index dropped successfully")

func (*Client) Find

func (c *Client) Find(ctx context.Context, collection string, filter any, results any, opts ...*options.FindOptions) error

Find finds all documents matching the filter and decodes them into results.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to search in
  • filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} for all documents
  • results: Pointer to a slice where found documents will be decoded (e.g., *[]User)
  • opts: Optional FindOptions for sorting, projection, limit, skip, etc.

Returns:

  • error: Returns error if operation fails or client is closed. Empty results is not an error

Example:

var users []User
filter := bson.M{"age": bson.M{"$gte": 18}}
opts := options.Find().SetLimit(10).SetSort(bson.M{"name": 1})
err := client.Find(ctx, "users", filter, &users, opts)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Found %d users\n", len(users))

func (*Client) FindOne

func (c *Client) FindOne(ctx context.Context, collection string, filter any, result any, opts ...*options.FindOneOptions) error

FindOne finds a single document matching the filter and decodes it into result.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to search in
  • filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} for all documents
  • result: Pointer to a variable where the found document will be decoded
  • opts: Optional FindOneOptions for sorting, projection, skip, etc.

Returns:

  • error: Returns ErrDocumentNotFound if no document matches, ErrClientClosed if client is closed, or operation error

Example:

var user User
err := client.FindOne(ctx, "users", bson.M{"email": "john@example.com"}, &user)
if err != nil {
    if errors.Is(err, mongo.ErrDocumentNotFound) {
        fmt.Println("User not found")
    }
    return err
}
fmt.Printf("Found user: %s\n", user.Name)

func (*Client) FindOneAndDelete

func (c *Client) FindOneAndDelete(ctx context.Context, collection string, filter any, result any, opts ...*options.FindOneAndDeleteOptions) error

FindOneAndDelete finds a single document, deletes it, and returns the deleted document. This is an atomic operation that prevents race conditions.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to search and delete from
  • filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
  • result: Pointer to a variable where the deleted document will be decoded
  • opts: Optional FindOneAndDeleteOptions for sorting, projection, collation, etc.

Returns:

  • error: Returns ErrDocumentNotFound if no document matches, or operation error

Example:

var deletedUser User
filter := bson.M{"email": "tobedeleted@example.com"}
err := client.FindOneAndDelete(ctx, "users", filter, &deletedUser)
if err != nil {
    if errors.Is(err, mongo.ErrDocumentNotFound) {
        fmt.Println("User not found")
    }
    return err
}
fmt.Printf("Deleted user: %s\n", deletedUser.Name)

func (*Client) FindOneAndReplace

func (c *Client) FindOneAndReplace(ctx context.Context, collection string, filter any, replacement any, result any, opts ...*options.FindOneAndReplaceOptions) error

FindOneAndReplace finds a single document, replaces it, and returns either the original or replaced document. This is an atomic operation that prevents race conditions.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to search and replace in
  • filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
  • replacement: The new document to replace with. Cannot contain update operators. The _id field will be preserved
  • result: Pointer to a variable where the document will be decoded (original or replaced, depending on options)
  • opts: Optional FindOneAndReplaceOptions. Use SetReturnDocument(options.After) to return the replaced document

Returns:

  • error: Returns ErrDocumentNotFound if no document matches, or operation error

Example:

var oldUser User
filter := bson.M{"_id": userID}
newUser := User{Name: "Updated Name", Email: "new@example.com", Status: "active"}
opts := options.FindOneAndReplace().SetReturnDocument(options.Before)
err := client.FindOneAndReplace(ctx, "users", filter, newUser, &oldUser, opts)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Old user name: %s\n", oldUser.Name)

func (*Client) FindOneAndUpdate

func (c *Client) FindOneAndUpdate(ctx context.Context, collection string, filter any, update any, result any, opts ...*options.FindOneAndUpdateOptions) error

FindOneAndUpdate finds a single document, updates it, and returns either the original or updated document. This is an atomic operation that prevents race conditions.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to search and update in
  • filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
  • update: Update operations to apply. Must use update operators like $set, $inc, etc.
  • result: Pointer to a variable where the document will be decoded (original or updated, depending on options)
  • opts: Optional FindOneAndUpdateOptions. Use SetReturnDocument(options.After) to return the updated document

Returns:

  • error: Returns ErrDocumentNotFound if no document matches, or operation error

Example:

var user User
filter := bson.M{"email": "john@example.com"}
update := bson.M{"$inc": bson.M{"login_count": 1}, "$set": bson.M{"last_login": time.Now()}}
opts := options.FindOneAndUpdate().SetReturnDocument(options.After)
err := client.FindOneAndUpdate(ctx, "users", filter, update, &user, opts)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("User %s logged in %d times\n", user.Name, user.LoginCount)

func (*Client) GetCollection

func (c *Client) GetCollection(collectionName string) *mongo.Collection

GetCollection returns a handle to the specified collection in the default database

func (*Client) GetCollectionFrom

func (c *Client) GetCollectionFrom(databaseName, collectionName string) *mongo.Collection

GetCollectionFrom returns a handle to the specified collection in the specified database

func (*Client) GetConfig

func (c *Client) GetConfig() models.Config

GetConfig returns a copy of the client configuration

func (*Client) GetDatabase

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

GetDatabase returns a handle to the specified database If name is empty, returns the default database from config

func (*Client) InsertMany

func (c *Client) InsertMany(ctx context.Context, collection string, documents []any) (*mongo.InsertManyResult, error)

InsertMany inserts multiple documents into the specified collection in a single operation.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection where documents will be inserted
  • documents: Slice of documents to insert. Each element can be a struct, bson.M, bson.D, or any serializable type

Returns:

  • *mongo.InsertManyResult: Contains InsertedIDs field with a map of insertion order to _id values
  • error: Returns error if insertion fails or client is closed

Example:

users := []any{
    User{Name: "John", Email: "john@example.com"},
    User{Name: "Jane", Email: "jane@example.com"},
}
result, err := client.InsertMany(ctx, "users", users)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Inserted %d documents\n", len(result.InsertedIDs))

func (*Client) InsertOne

func (c *Client) InsertOne(ctx context.Context, collection string, document any) (*mongo.InsertOneResult, error)

InsertOne inserts a single document into the specified collection.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection where the document will be inserted
  • document: The document to insert. Can be a struct, bson.M, bson.D, or any serializable type

Returns:

  • *mongo.InsertOneResult: Contains the InsertedID field with the _id of the inserted document
  • error: Returns error if insertion fails or client is closed

Example:

type User struct {
    Name  string `bson:"name"`
    Email string `bson:"email"`
}
result, err := client.InsertOne(ctx, "users", User{Name: "John", Email: "john@example.com"})
if err != nil {
    log.Fatal(err)
}
fmt.Println("Inserted ID:", result.InsertedID)

func (*Client) IsClosed

func (c *Client) IsClosed() bool

IsClosed returns true if the client has been closed

func (*Client) IsConnected

func (c *Client) IsConnected(ctx context.Context) bool

IsConnected checks if the client is connected to MongoDB

func (*Client) ListCollections

func (c *Client) ListCollections(ctx context.Context) ([]string, error)

ListCollections retrieves the names of all collections in the default database.

Parameters:

  • ctx: Context for cancellation and timeout control

Returns:

  • []string: Slice of collection names in the database
  • error: Returns error if operation fails or client is closed

Example:

collections, err := client.ListCollections(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Found %d collections:\n", len(collections))
for _, name := range collections {
    fmt.Println("-", name)
}

func (*Client) ListDatabases

func (c *Client) ListDatabases(ctx context.Context, filter interface{}) ([]string, error)

ListDatabases lists all databases on the MongoDB server

func (*Client) ListIndexes

func (c *Client) ListIndexes(ctx context.Context, collection string) ([]bson.M, error)

ListIndexes retrieves information about all indexes on the specified collection.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to list indexes from

Returns:

  • []bson.M: Slice of index specifications, each containing name, keys, unique, sparse, etc.
  • error: Returns error if operation fails or client is closed

Example:

indexes, err := client.ListIndexes(ctx, "users")
if err != nil {
    log.Fatal(err)
}
for _, index := range indexes {
    fmt.Printf("Index: %s, Keys: %v\n", index["name"], index["key"])
}

func (*Client) Ping

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

Ping verifies the connection to MongoDB Returns an error if connection verification fails

func (*Client) ReplaceOne

func (c *Client) ReplaceOne(ctx context.Context, collection string, filter any, replacement any, opts ...*options.ReplaceOptions) (*mongo.UpdateResult, error)

ReplaceOne replaces a single document matching the filter with a new document. Unlike UpdateOne, this replaces the entire document (except _id) rather than modifying specific fields.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to replace in
  • filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
  • replacement: The new document to replace with. Cannot contain update operators like $set. The _id field will be preserved
  • opts: Optional ReplaceOptions for upsert, bypass validation, etc.

Returns:

  • *mongo.UpdateResult: Contains MatchedCount, ModifiedCount, UpsertedCount, and UpsertedID
  • error: Returns error if operation fails or client is closed

Example:

filter := bson.M{"_id": userID}
newUser := User{Name: "John Doe", Email: "john@example.com", Age: 30}
result, err := client.ReplaceOne(ctx, "users", filter, newUser)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Replaced %d document(s)\n", result.ModifiedCount)

func (*Client) StartSession

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

StartSession starts a new session for transaction support

func (*Client) UpdateMany

func (c *Client) UpdateMany(ctx context.Context, collection string, filter any, update any, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

UpdateMany updates all documents matching the filter.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to update in
  • filter: Query filter to match documents. Can be bson.M, bson.D, or a struct. Use bson.M{} to update all documents
  • update: Update operations to apply. Must use update operators like $set, $inc, etc. (e.g., bson.M{"$set": bson.M{"status": "active"}})
  • opts: Optional UpdateOptions for upsert, bypass validation, etc.

Returns:

  • *mongo.UpdateResult: Contains MatchedCount, ModifiedCount, UpsertedCount, and UpsertedID
  • error: Returns error if operation fails or client is closed

Example:

filter := bson.M{"status": "pending"}
update := bson.M{"$set": bson.M{"status": "processed", "processed_at": time.Now()}}
result, err := client.UpdateMany(ctx, "orders", filter, update)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Modified %d document(s)\n", result.ModifiedCount)

func (*Client) UpdateOne

func (c *Client) UpdateOne(ctx context.Context, collection string, filter any, update any, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

UpdateOne updates a single document matching the filter.

Parameters:

  • ctx: Context for cancellation and timeout control
  • collection: Name of the collection to update in
  • filter: Query filter to match the document. Can be bson.M, bson.D, or a struct
  • update: Update operations to apply. Must use update operators like $set, $inc, etc. (e.g., bson.M{"$set": bson.M{"age": 30}})
  • opts: Optional UpdateOptions for upsert, bypass validation, etc.

Returns:

  • *mongo.UpdateResult: Contains MatchedCount, ModifiedCount, UpsertedCount, and UpsertedID
  • error: Returns error if operation fails or client is closed

Example:

filter := bson.M{"email": "john@example.com"}
update := bson.M{"$set": bson.M{"age": 31}, "$inc": bson.M{"login_count": 1}}
result, err := client.UpdateOne(ctx, "users", filter, update)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Modified %d document(s)\n", result.ModifiedCount)

func (*Client) UseSession

func (c *Client) UseSession(ctx context.Context, fn func(mongo.SessionContext) error) error

UseSession executes a function within a session

type Config

type Config = models.Config

Config holds MongoDB client configuration

type CountOptions

type CountOptions = options.CountOptions

CountOptions is a convenient alias for options.CountOptions

type CreateCollectionOptions

type CreateCollectionOptions = options.CreateCollectionOptions

CreateCollectionOptions is a convenient alias for options.CreateCollectionOptions

type D

type D = bson.D

D is a convenient alias for bson.D

type DeleteOptions

type DeleteOptions = options.DeleteOptions

DeleteOptions is a convenient alias for options.DeleteOptions

type DistinctOptions

type DistinctOptions = options.DistinctOptions

DistinctOptions is a convenient alias for options.DistinctOptions

type E

type E = bson.E

E is a convenient alias for bson.E

type FindOneAndDeleteOptions

type FindOneAndDeleteOptions = options.FindOneAndDeleteOptions

FindOneAndDeleteOptions is a convenient alias for options.FindOneAndDeleteOptions

type FindOneAndReplaceOptions

type FindOneAndReplaceOptions = options.FindOneAndReplaceOptions

FindOneAndReplaceOptions is a convenient alias for options.FindOneAndReplaceOptions

type FindOneAndUpdateOptions

type FindOneAndUpdateOptions = options.FindOneAndUpdateOptions

FindOneAndUpdateOptions is a convenient alias for options.FindOneAndUpdateOptions

type FindOneOptions

type FindOneOptions = options.FindOneOptions

FindOneOptions is a convenient alias for options.FindOneOptions

type FindOptions

type FindOptions = options.FindOptions

FindOptions is a convenient alias for options.FindOptions

type IndexModel

type IndexModel = mongo.IndexModel

IndexModel represents an index to be created

type IndexOptions

type IndexOptions = options.IndexOptions

IndexOptions is a convenient alias for options.IndexOptions

type InsertManyOptions

type InsertManyOptions = options.InsertManyOptions

InsertManyOptions is a convenient alias for options.InsertManyOptions

type InsertOneOptions

type InsertOneOptions = options.InsertOneOptions

InsertOneOptions is a convenient alias for options.InsertOneOptions

type M

type M = bson.M

M is a convenient alias for bson.M

type ObjectID

type ObjectID = primitive.ObjectID

MongoDB primitive types for convenience

type Option

type Option = models.Option

Option is a function that modifies Config

type QueryBuilder

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

QueryBuilder provides a fluent interface for building MongoDB queries

func NewQueryBuilder

func NewQueryBuilder() *QueryBuilder

NewQueryBuilder creates a new QueryBuilder instance

func (*QueryBuilder) And

func (qb *QueryBuilder) And(conditions ...bson.D) *QueryBuilder

And adds an and condition

func (*QueryBuilder) Build

func (qb *QueryBuilder) Build() (bson.D, *options.FindOptions)

Build returns the filter and options

func (*QueryBuilder) BuildFilter

func (qb *QueryBuilder) BuildFilter() bson.D

BuildFilter returns only the filter

func (*QueryBuilder) BuildOptions

func (qb *QueryBuilder) BuildOptions() *options.FindOptions

BuildOptions returns only the options

func (*QueryBuilder) Equals

func (qb *QueryBuilder) Equals(key string, value interface{}) *QueryBuilder

Equals adds an equality filter

func (*QueryBuilder) Exists

func (qb *QueryBuilder) Exists(key string, exists bool) *QueryBuilder

Exists adds an exists filter

func (*QueryBuilder) Filter

func (qb *QueryBuilder) Filter(key string, value interface{}) *QueryBuilder

Filter adds a filter condition to the query

func (*QueryBuilder) GreaterThan

func (qb *QueryBuilder) GreaterThan(key string, value interface{}) *QueryBuilder

GreaterThan adds a greater than filter

func (*QueryBuilder) GreaterThanOrEqual

func (qb *QueryBuilder) GreaterThanOrEqual(key string, value interface{}) *QueryBuilder

GreaterThanOrEqual adds a greater than or equal filter

func (*QueryBuilder) In

func (qb *QueryBuilder) In(key string, values ...interface{}) *QueryBuilder

In adds an in filter

func (*QueryBuilder) LessThan

func (qb *QueryBuilder) LessThan(key string, value interface{}) *QueryBuilder

LessThan adds a less than filter

func (*QueryBuilder) LessThanOrEqual

func (qb *QueryBuilder) LessThanOrEqual(key string, value interface{}) *QueryBuilder

LessThanOrEqual adds a less than or equal filter

func (*QueryBuilder) Limit

func (qb *QueryBuilder) Limit(limit int64) *QueryBuilder

Limit sets the maximum number of documents to return

func (*QueryBuilder) Nor

func (qb *QueryBuilder) Nor(conditions ...bson.D) *QueryBuilder

Nor adds a nor condition

func (*QueryBuilder) NotEquals

func (qb *QueryBuilder) NotEquals(key string, value interface{}) *QueryBuilder

NotEquals adds a not equals filter

func (*QueryBuilder) NotIn

func (qb *QueryBuilder) NotIn(key string, values ...interface{}) *QueryBuilder

NotIn adds a not in filter

func (*QueryBuilder) Or

func (qb *QueryBuilder) Or(conditions ...bson.D) *QueryBuilder

Or adds an or condition

func (*QueryBuilder) Project

func (qb *QueryBuilder) Project(projection interface{}) *QueryBuilder

Project sets the projection

func (*QueryBuilder) Regex

func (qb *QueryBuilder) Regex(key string, pattern string, options string) *QueryBuilder

Regex adds a regex filter

func (*QueryBuilder) Skip

func (qb *QueryBuilder) Skip(skip int64) *QueryBuilder

Skip sets the number of documents to skip

func (*QueryBuilder) Sort

func (qb *QueryBuilder) Sort(field string, ascending bool) *QueryBuilder

Sort sets the sort order

func (*QueryBuilder) SortBy

func (qb *QueryBuilder) SortBy(sort interface{}) *QueryBuilder

SortBy sets custom sort order

type ReplaceOptions

type ReplaceOptions = options.ReplaceOptions

ReplaceOptions is a convenient alias for options.ReplaceOptions

type UpdateBuilder

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

UpdateBuilder provides a fluent interface for building update operations

func NewUpdateBuilder

func NewUpdateBuilder() *UpdateBuilder

NewUpdateBuilder creates a new UpdateBuilder instance

func (*UpdateBuilder) AddToSet

func (ub *UpdateBuilder) AddToSet(key string, value interface{}) *UpdateBuilder

AddToSet adds value to array if not already present

func (*UpdateBuilder) Build

func (ub *UpdateBuilder) Build() bson.D

Build returns the update document

func (*UpdateBuilder) CurrentDate

func (ub *UpdateBuilder) CurrentDate(key string) *UpdateBuilder

CurrentDate sets field to current date

func (*UpdateBuilder) Inc

func (ub *UpdateBuilder) Inc(key string, value interface{}) *UpdateBuilder

Inc increments field values

func (*UpdateBuilder) Max

func (ub *UpdateBuilder) Max(key string, value interface{}) *UpdateBuilder

Max updates field if specified value is greater than current value

func (*UpdateBuilder) Min

func (ub *UpdateBuilder) Min(key string, value interface{}) *UpdateBuilder

Min updates field if specified value is less than current value

func (*UpdateBuilder) Mul

func (ub *UpdateBuilder) Mul(key string, value interface{}) *UpdateBuilder

Mul multiplies field values

func (*UpdateBuilder) Pop

func (ub *UpdateBuilder) Pop(key string, first bool) *UpdateBuilder

Pop removes first or last element from array

func (*UpdateBuilder) Pull

func (ub *UpdateBuilder) Pull(key string, value interface{}) *UpdateBuilder

Pull removes all instances of value from array

func (*UpdateBuilder) Push

func (ub *UpdateBuilder) Push(key string, value interface{}) *UpdateBuilder

Push appends value to array

func (*UpdateBuilder) Rename

func (ub *UpdateBuilder) Rename(oldName string, newName string) *UpdateBuilder

Rename renames a field

func (*UpdateBuilder) Set

func (ub *UpdateBuilder) Set(key string, value interface{}) *UpdateBuilder

Set sets field values

func (*UpdateBuilder) SetMultiple

func (ub *UpdateBuilder) SetMultiple(fields map[string]interface{}) *UpdateBuilder

SetMultiple sets multiple field values at once

func (*UpdateBuilder) Unset

func (ub *UpdateBuilder) Unset(keys ...string) *UpdateBuilder

Unset removes fields

type UpdateOptions

type UpdateOptions = options.UpdateOptions

UpdateOptions is a convenient alias for options.UpdateOptions

type WriteModel

type WriteModel = mongo.WriteModel

WriteModel is an interface for bulk write operations

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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