mongo_kit

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2026 License: MIT Imports: 10 Imported by: 0

README

mongo-kit-go

A clean, type-safe MongoDB client library for Go using the Repository pattern with generics.

Go Version License

Installation

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

Quick Start

import (
    "context"
    mongokit "github.com/edaniel30/mongo-kit-go"
    "go.mongodb.org/mongo-driver/bson/primitive"
)

// Define your model
type User struct {
    ID    primitive.ObjectID `bson:"_id,omitempty"`
    Name  string             `bson:"name"`
    Email string             `bson:"email"`
    Age   int                `bson:"age"`
}

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

// Create repository
userRepo := mongokit.NewRepository[User](client, "users")

// Use it!
ctx := context.Background()

// Create
user := User{Name: "Alice", Email: "alice@example.com", Age: 25}
id, _ := userRepo.Create(ctx, user)

// Find
user, _ := userRepo.FindByID(ctx, id)
users, _ := userRepo.Find(ctx, map[string]any{"age": map[string]any{"$gte": 18}})

// Update
update := map[string]any{"$set": map[string]any{"age": 26}}
userRepo.UpdateByID(ctx, id, update)

// Delete
userRepo.DeleteByID(ctx, id)

Configuration Options

Option Description Default
WithURI(uri) MongoDB connection URI mongodb://localhost:27017
WithDatabase(name) Default database name default
WithMaxPoolSize(size) Max connections 100
WithTimeout(duration) Operation timeout 10s
WithClientOptions(opts) Custom driver options nil

Query Builder

Build complex queries with a fluent interface:

qb := mongo_kit.NewQueryBuilder().
    Equals("status", "active").
    GreaterThan("age", 18).
    In("role", "admin", "moderator").
    Sort("name", true).
    Limit(10)

users, _ := userRepo.FindWithBuilder(ctx, qb)

Available operators: Equals, NotEquals, GreaterThan, LessThan, In, NotIn, Exists, Regex, And, Or, Nor

Update Builder

Build complex updates:

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

userRepo.UpdateByID(ctx, id, ub.Build())

Available operations: Set, Unset, Inc, Mul, Min, Max, Push, Pull, AddToSet, Pop, CurrentDate, Rename

Aggregation Builder

Build aggregation pipelines:

ab := mongo_kit.NewAggregationBuilder().
    Match(bson.M{"status": "active"}).
    Group("$category", bson.M{
        "count": bson.M{"$sum": 1},
        "total": bson.M{"$sum": "$amount"},
    }).
    Sort(bson.D{{Key: "total", Value: -1}})

// Use primitive.M for aggregation results
aggRepo := mongo_kit.NewRepository[primitive.M](client, "orders")
results, _ := aggRepo.Aggregate(ctx, ab.Build())

Examples

Complete working examples are available in the examples/ directory:

Example Description
basic_crud Create, Read, Update, Delete operations
query_builders Complex queries with QueryBuilder
update_builders Update operations with UpdateBuilder
aggregations Aggregation pipelines with AggregationBuilder

Run any example:

go run ./examples/basic_crud/main.go

Documentation

Comprehensive guides for each component:

Guide Description
operations.md All repository operations (CRUD, bulk, aggregations)
query.md QueryBuilder, UpdateBuilder, AggregationBuilder
repository.md Repository pattern with generics

Repository API

Create Operations
  • Create(ctx, doc) - Insert single document
  • CreateMany(ctx, docs) - Insert multiple documents
Read Operations
  • FindByID(ctx, id) - Find by ObjectID or string
  • FindOne(ctx, filter, opts...) - Find single document
  • Find(ctx, filter, opts...) - Find multiple documents
  • FindAll(ctx, opts...) - Find all documents
  • FindWithBuilder(ctx, qb) - Find with QueryBuilder
  • FindOneWithBuilder(ctx, qb) - Find one with QueryBuilder
Update Operations
  • UpdateByID(ctx, id, update) - Update by ID
  • UpdateOne(ctx, filter, update) - Update single document
  • UpdateMany(ctx, filter, update) - Update multiple documents
  • Upsert(ctx, filter, update) - Insert or update
Delete Operations
  • DeleteByID(ctx, id) - Delete by ID
  • DeleteOne(ctx, filter) - Delete single document
  • DeleteMany(ctx, filter) - Delete multiple documents
Query Operations
  • Count(ctx, filter) - Count matching documents
  • CountAll(ctx) - Count all documents
  • CountWithBuilder(ctx, qb) - Count with QueryBuilder
  • EstimatedCount(ctx) - Fast approximate count
  • Exists(ctx, filter) - Check if document exists
  • ExistsByID(ctx, id) - Check if ID exists
  • ExistsWithBuilder(ctx, qb) - Check existence with QueryBuilder
Other Operations
  • Aggregate(ctx, pipeline, opts...) - Run aggregation pipeline
  • Drop(ctx) - Drop entire collection

Contributing

Contributions are welcome! Please open an issue or submit a pull request.

License

MIT License - see the LICENSE file for details.

Documentation

Overview

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

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrClientClosed is returned when an operation is attempted on a closed client.
	// Use errors.Is(err, mongo.ErrClientClosed) to check for this error.
	ErrClientClosed = errors.New("mongo: client is closed")
)

Functions

This section is empty.

Types

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 any, 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 any) *AggregationBuilder

Match adds a $match stage.

func (*AggregationBuilder) Project

func (ab *AggregationBuilder) Project(projection any) *AggregationBuilder

Project adds a $project stage.

func (*AggregationBuilder) Skip

Skip adds a $skip stage.

func (*AggregationBuilder) Sort

func (ab *AggregationBuilder) Sort(sort any) *AggregationBuilder

Sort adds a $sort stage.

func (*AggregationBuilder) Unwind

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

Unwind adds an $unwind stage.

type Client

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

Client wraps the MongoDB driver client with convenience methods. It provides a simpler API for common operations while maintaining thread-safety. The client is safe for concurrent use across multiple goroutines.

While Client is exported for advanced use cases, users are encouraged to primarily interact with the database through Repository[T] for type-safe operations.

func New

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

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

The client will automatically:

  • Validate the configuration
  • Connect to MongoDB
  • Verify the connection with a ping

Example:

client, err := mongo_kit.New(
    mongo_kit.DefaultConfig(),
    mongo_kit.WithURI("mongodb://localhost:27017"),
    mongo_kit.WithDatabase("myapp"),
    mongo_kit.WithMaxPoolSize(200),
)
if err != nil {
    log.Fatal(err)
}
defer client.Close(context.Background())

Returns an error if:

  • Configuration is invalid
  • Connection to MongoDB fails
  • Ping verification fails

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. Calling Close multiple times is safe and will only disconnect once.

Example:

defer client.Close(context.Background())

func (*Client) CreateCollection

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

CreateCollection creates a new collection with optional configuration. If the collection already exists, this is a no-op (no error is returned).

Example:

err := client.CreateCollection(ctx, "users", options.CreateCollection().SetCapped(true).SetSizeInBytes(1000000))

func (*Client) CreateIndexes

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

CreateIndexes creates multiple indexes on the specified collection. Returns the names of the created indexes.

Example:

indexes := []mongo.IndexModel{
    {
        Keys: bson.D{{Key: "email", Value: 1}},
        Options: options.Index().SetUnique(true),
    },
    {
        Keys: bson.D{{Key: "created_at", Value: -1}},
    },
}
names, err := client.CreateIndexes(ctx, "users", indexes)

type Config

type Config struct {
	URI      string // MongoDB connection URI (required)
	Database string // Default database name (required)

	MaxPoolSize   uint64                 // Maximum number of connections in the connection pool (default: 100)
	Timeout       time.Duration          // Default timeout for all operations (default: 10s)
	ClientOptions *options.ClientOptions // Direct access to MongoDB driver options for advanced use cases
}

Config holds the MongoDB client configuration. Use DefaultConfig() to get sensible defaults, then customize with Option functions.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible default values. This is the recommended starting point for most applications.

Default values:

  • URI: "mongodb://localhost:27017"
  • Database: "default"
  • MaxPoolSize: 100
  • Timeout: 10 seconds

Example:

cfg := mongo_kit.DefaultConfig()
client, err := mongo_kit.New(cfg, mongo_kit.WithURI("mongodb://prod:27017"))

type ConfigError added in v0.2.0

type ConfigError struct {
	Field   string // The configuration field that caused the error (optional)
	Message string // Human-readable error message
}

ConfigError represents a configuration validation error. Users can access the Field and Message to understand what configuration is invalid.

func (*ConfigError) Error added in v0.2.0

func (e *ConfigError) Error() string

type ConnectionError added in v0.2.0

type ConnectionError struct {
	Cause error // The underlying error that caused the connection failure
}

ConnectionError represents a connection failure to MongoDB. The Cause field contains the underlying error from the MongoDB driver.

func (*ConnectionError) Error added in v0.2.0

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap added in v0.2.0

func (e *ConnectionError) Unwrap() error

type OperationError added in v0.2.0

type OperationError struct {
	Op    string // The name of the operation that failed (e.g., "find", "insert", "update")
	Cause error  // The underlying error from MongoDB driver
}

OperationError represents an error that occurred during a database operation. The Op field identifies which operation failed, and Cause contains the underlying error.

func (*OperationError) Error added in v0.2.0

func (e *OperationError) Error() string

func (*OperationError) Unwrap added in v0.2.0

func (e *OperationError) Unwrap() error

type Option

type Option func(*Config)

Option is a function that modifies a Config. Use Option functions with New() to customize the configuration.

func WithClientOptions added in v0.2.0

func WithClientOptions(opts *options.ClientOptions) Option

WithClientOptions allows you to directly configure the underlying MongoDB driver options. This is an escape hatch for advanced configurations not covered by the basic options.

Use this when you need fine-grained control over:

  • Minimum pool size
  • Retry behavior
  • TLS/SSL settings
  • Compression
  • Read preferences
  • Write concerns
  • And more...

Example:

clientOpts := options.Client()
clientOpts.SetMinPoolSize(10)
clientOpts.SetRetryWrites(true)
clientOpts.SetReadPreference(readpref.Secondary())
mongo_kit.WithClientOptions(clientOpts)

Note: Settings applied via WithClientOptions will override basic options like MaxPoolSize.

func WithDatabase

func WithDatabase(database string) Option

WithDatabase sets the default database name. All operations without an explicit database will use this database.

Example:

mongo_kit.WithDatabase("myapp")

func WithMaxPoolSize

func WithMaxPoolSize(size uint64) Option

WithMaxPoolSize sets the maximum number of connections in the connection pool. Default is 100. Increase for high-concurrency applications.

Example:

mongo_kit.WithMaxPoolSize(200)

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the default timeout for all database operations. This timeout applies to operations that don't specify their own context timeout. Default is 10 seconds.

Example:

mongo_kit.WithTimeout(30 * time.Second)

func WithURI

func WithURI(uri string) Option

WithURI sets the MongoDB connection URI.

Example:

mongo_kit.WithURI("mongodb://user:pass@localhost:27017")
mongo_kit.WithURI("mongodb+srv://cluster.mongodb.net")

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) AndConditions added in v0.2.0

func (qb *QueryBuilder) AndConditions(builders ...*QueryBuilder) *QueryBuilder

AndConditions combines multiple QueryBuilders with $and logic.

func (*QueryBuilder) Build

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

Build returns the filter and options.

func (*QueryBuilder) Equals

func (qb *QueryBuilder) Equals(key string, value any) *QueryBuilder

Equals adds an equality filter. Alias for 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 any) *QueryBuilder

Filter adds a filter condition to the query.

func (*QueryBuilder) GetFilter added in v0.2.0

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

GetFilter returns the filter without options.

func (*QueryBuilder) GreaterThan

func (qb *QueryBuilder) GreaterThan(key string, value any) *QueryBuilder

GreaterThan adds a greater than filter.

func (*QueryBuilder) GreaterThanOrEqual

func (qb *QueryBuilder) GreaterThanOrEqual(key string, value any) *QueryBuilder

GreaterThanOrEqual adds a greater than or equal filter.

func (*QueryBuilder) In

func (qb *QueryBuilder) In(key string, values ...any) *QueryBuilder

In adds an in filter.

func (*QueryBuilder) LessThan

func (qb *QueryBuilder) LessThan(key string, value any) *QueryBuilder

LessThan adds a less than filter.

func (*QueryBuilder) LessThanOrEqual

func (qb *QueryBuilder) LessThanOrEqual(key string, value any) *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) NorConditions added in v0.2.0

func (qb *QueryBuilder) NorConditions(builders ...*QueryBuilder) *QueryBuilder

NorConditions combines multiple QueryBuilders with $nor logic.

func (*QueryBuilder) NotEquals

func (qb *QueryBuilder) NotEquals(key string, value any) *QueryBuilder

NotEquals adds a not equals filter.

func (*QueryBuilder) NotIn

func (qb *QueryBuilder) NotIn(key string, values ...any) *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) OrConditions added in v0.2.0

func (qb *QueryBuilder) OrConditions(builders ...*QueryBuilder) *QueryBuilder

OrConditions combines multiple QueryBuilders with $or logic.

func (*QueryBuilder) Project

func (qb *QueryBuilder) Project(projection any) *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 adds a field to the sort order.

func (*QueryBuilder) SortBy

func (qb *QueryBuilder) SortBy(sort any) *QueryBuilder

SortBy sets custom sort order, replacing any previously set sort fields.

func (*QueryBuilder) Where added in v0.2.0

func (qb *QueryBuilder) Where(expression any) *QueryBuilder

Where adds a raw MongoDB expression to the filter.

type Repository added in v0.2.0

type Repository[T any] struct {
	// contains filtered or unexported fields
}

Repository provides a type-safe, collection-specific interface for database operations.

func NewRepository added in v0.2.0

func NewRepository[T any](client *Client, collection string) *Repository[T]

NewRepository creates a new type-safe repository for the specified collection.

func (*Repository[T]) Aggregate added in v0.2.0

func (r *Repository[T]) Aggregate(ctx context.Context, pipeline any, opts ...*options.AggregateOptions) ([]T, error)

Aggregate executes an aggregation pipeline and returns typed results.

func (*Repository[T]) Collection added in v0.2.0

func (r *Repository[T]) Collection() string

Collection returns the name of the collection this repository operates on.

func (*Repository[T]) Count added in v0.2.0

func (r *Repository[T]) Count(ctx context.Context, filter any, opts ...*options.CountOptions) (int64, error)

Count returns the number of documents matching the filter.

func (*Repository[T]) CountAll added in v0.2.0

func (r *Repository[T]) CountAll(ctx context.Context, opts ...*options.CountOptions) (int64, error)

CountAll counts all documents in the collection.

func (*Repository[T]) CountWithBuilder added in v0.2.0

func (r *Repository[T]) CountWithBuilder(ctx context.Context, qb *QueryBuilder) (int64, error)

CountWithBuilder counts documents using a QueryBuilder filter.

func (*Repository[T]) Create added in v0.2.0

func (r *Repository[T]) Create(ctx context.Context, document T) (any, error)

Create inserts a new document and returns its ID.

func (*Repository[T]) CreateMany added in v0.2.0

func (r *Repository[T]) CreateMany(ctx context.Context, documents []T) ([]any, error)

CreateMany inserts multiple documents and returns their IDs.

func (*Repository[T]) DeleteByID added in v0.2.0

func (r *Repository[T]) DeleteByID(ctx context.Context, id any) (*mongo.DeleteResult, error)

DeleteByID deletes a single document by its _id field.

func (*Repository[T]) DeleteMany added in v0.2.0

func (r *Repository[T]) DeleteMany(ctx context.Context, filter any) (*mongo.DeleteResult, error)

DeleteMany deletes all documents matching the filter.

func (*Repository[T]) DeleteOne added in v0.2.0

func (r *Repository[T]) DeleteOne(ctx context.Context, filter any) (*mongo.DeleteResult, error)

DeleteOne deletes a single document matching the filter.

func (*Repository[T]) Drop added in v0.2.0

func (r *Repository[T]) Drop(ctx context.Context) error

Drop deletes the entire collection. WARNING: This permanently deletes all documents and indexes.

func (*Repository[T]) EstimatedCount added in v0.2.0

func (r *Repository[T]) EstimatedCount(ctx context.Context, opts ...*options.EstimatedDocumentCountOptions) (int64, error)

EstimatedCount returns an estimated count using collection metadata. Faster than Count but may be less accurate.

func (*Repository[T]) Exists added in v0.2.0

func (r *Repository[T]) Exists(ctx context.Context, filter any) (bool, error)

Exists checks if at least one document matching the filter exists.

func (*Repository[T]) ExistsByID added in v0.2.0

func (r *Repository[T]) ExistsByID(ctx context.Context, id any) (bool, error)

ExistsByID checks if a document with the given _id exists.

func (*Repository[T]) ExistsWithBuilder added in v0.2.0

func (r *Repository[T]) ExistsWithBuilder(ctx context.Context, qb *QueryBuilder) (bool, error)

ExistsWithBuilder checks if at least one document matching the QueryBuilder exists.

func (*Repository[T]) Find added in v0.2.0

func (r *Repository[T]) Find(ctx context.Context, filter any, opts ...*options.FindOptions) ([]T, error)

Find finds all documents matching the filter.

func (*Repository[T]) FindAll added in v0.2.0

func (r *Repository[T]) FindAll(ctx context.Context, opts ...*options.FindOptions) ([]T, error)

FindAll returns all documents in the collection.

func (*Repository[T]) FindByID added in v0.2.0

func (r *Repository[T]) FindByID(ctx context.Context, id any) (*T, error)

FindByID finds a single document by its _id field. Returns mongo.ErrNoDocuments if not found.

func (*Repository[T]) FindOne added in v0.2.0

func (r *Repository[T]) FindOne(ctx context.Context, filter any, opts ...*options.FindOneOptions) (*T, error)

FindOne finds a single document matching the filter. Returns mongo.ErrNoDocuments if not found.

func (*Repository[T]) FindOneWithBuilder added in v0.2.0

func (r *Repository[T]) FindOneWithBuilder(ctx context.Context, qb *QueryBuilder) (*T, error)

FindOneWithBuilder finds a single document using a QueryBuilder. Returns mongo.ErrNoDocuments if not found.

func (*Repository[T]) FindWithBuilder added in v0.2.0

func (r *Repository[T]) FindWithBuilder(ctx context.Context, qb *QueryBuilder) ([]T, error)

FindWithBuilder finds documents using a QueryBuilder for complex queries.

func (*Repository[T]) UpdateByID added in v0.2.0

func (r *Repository[T]) UpdateByID(ctx context.Context, id any, update any, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

UpdateByID updates a single document by its _id field.

func (*Repository[T]) UpdateMany added in v0.2.0

func (r *Repository[T]) UpdateMany(ctx context.Context, filter any, update any, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

UpdateMany updates all documents matching the filter.

func (*Repository[T]) UpdateOne added in v0.2.0

func (r *Repository[T]) UpdateOne(ctx context.Context, filter any, update any, opts ...*options.UpdateOptions) (*mongo.UpdateResult, error)

UpdateOne updates a single document matching the filter.

func (*Repository[T]) Upsert added in v0.2.0

func (r *Repository[T]) Upsert(ctx context.Context, filter any, update any) (*mongo.UpdateResult, error)

Upsert updates a document if it exists, or inserts it if it doesn't.

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 any) *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 any) *UpdateBuilder

Inc increments field values.

func (*UpdateBuilder) Max

func (ub *UpdateBuilder) Max(key string, value any) *UpdateBuilder

Max updates field if specified value is greater than current value.

func (*UpdateBuilder) Min

func (ub *UpdateBuilder) Min(key string, value any) *UpdateBuilder

Min updates field if specified value is less than current value.

func (*UpdateBuilder) Mul

func (ub *UpdateBuilder) Mul(key string, value any) *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 any) *UpdateBuilder

Pull removes all instances of value from array.

func (*UpdateBuilder) Push

func (ub *UpdateBuilder) Push(key string, value any) *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 any) *UpdateBuilder

Set sets field values.

func (*UpdateBuilder) Unset

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

Unset removes fields.

Directories

Path Synopsis
examples
aggregations command
basic_crud command
query_builders command
update_builders command

Jump to

Keyboard shortcuts

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