mongodb

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2025 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidReadPreference = errors.New("invalid read preference")
	ErrInvalidWriteConcern   = errors.New("invalid write concern")
)

Sentinel errors for MongoDB configuration validation

Functions

func NewConnection

func NewConnection(cfg *config.DatabaseConfig, log logger.Logger) (database.Interface, error)

NewConnection creates a new MongoDB connection

Types

type Builder

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

Builder provides a fluent interface for building MongoDB queries and aggregation pipelines This follows the Squirrel pattern but for MongoDB's document-oriented operations.

func Match

func Match(filter bson.M) *Builder

Match creates a new builder with initial match condition

func NewBuilder

func NewBuilder() *Builder

NewBuilder creates a new MongoDB query builder

func Pipeline

func Pipeline(stages ...bson.M) *Builder

Pipeline creates a new builder with an initial pipeline stage

func Select

func Select(fields ...string) *Builder

Select creates a new builder with initial field selection

func Where

func Where(field string, value any) *Builder

Where creates a new builder with initial where condition

func (*Builder) AddGroup

func (b *Builder) AddGroup(group bson.M) *Builder

AddGroup adds a $group stage

func (*Builder) AddLimit

func (b *Builder) AddLimit(limit int64) *Builder

AddLimit adds a $limit stage

func (*Builder) AddLookup

func (b *Builder) AddLookup(from, localField, foreignField, as string) *Builder

AddLookup adds a $lookup stage for joins

func (*Builder) AddMatch

func (b *Builder) AddMatch(filter bson.M) *Builder

AddMatch adds a $match stage

func (*Builder) AddProject

func (b *Builder) AddProject(projection bson.M) *Builder

AddProject adds a $project stage

func (*Builder) AddSkip

func (b *Builder) AddSkip(skip int64) *Builder

AddSkip adds a $skip stage

func (*Builder) AddSort

func (b *Builder) AddSort(sort bson.D) *Builder

AddSort adds a $sort stage

func (*Builder) AddStage

func (b *Builder) AddStage(stage bson.M) *Builder

AddStage adds a custom aggregation stage

func (*Builder) AddUnwind

func (b *Builder) AddUnwind(field string) *Builder

AddUnwind adds an $unwind stage

func (*Builder) Clone

func (b *Builder) Clone() *Builder

Clone creates a copy of the builder

func (*Builder) Exclude

func (b *Builder) Exclude(fields ...string) *Builder

Exclude excludes specific fields from the result

func (*Builder) GetLimit

func (b *Builder) GetLimit() *int64

GetLimit returns the current limit value

func (*Builder) GetProjectionFields

func (b *Builder) GetProjectionFields() []string

GetProjectionFields returns the fields being projected

func (*Builder) GetSkip

func (b *Builder) GetSkip() *int64

GetSkip returns the current skip value

func (*Builder) GetSortFields

func (b *Builder) GetSortFields() []string

GetSortFields returns the fields being sorted

func (*Builder) GetState

func (b *Builder) GetState() BuilderState

GetState returns the current builder state for testing purposes

func (*Builder) HasFilter

func (b *Builder) HasFilter() bool

HasFilter returns true if the builder has filter conditions

func (*Builder) HasPagination

func (b *Builder) HasPagination() bool

HasPagination returns true if the builder has skip or limit set

func (*Builder) HasProjection

func (b *Builder) HasProjection() bool

HasProjection returns true if the builder has projection settings

func (*Builder) HasSort

func (b *Builder) HasSort() bool

HasSort returns true if the builder has sort conditions

func (*Builder) Limit

func (b *Builder) Limit(count int64) *Builder

Limit sets the maximum number of documents to return

func (*Builder) Offset

func (b *Builder) Offset(count int64) *Builder

Offset is an alias for Skip (SQL-like naming)

func (*Builder) OrderBy

func (b *Builder) OrderBy(field string) *Builder

OrderBy adds a sort field in ascending order

func (*Builder) OrderByAsc

func (b *Builder) OrderByAsc(field string) *Builder

OrderByAsc adds a sort field in ascending order (alias for OrderBy)

func (*Builder) OrderByDesc

func (b *Builder) OrderByDesc(field string) *Builder

OrderByDesc adds a sort field in descending order

func (*Builder) ProjectElemMatch

func (b *Builder) ProjectElemMatch(field string, condition any) *Builder

ProjectElemMatch projects elements that match a condition

func (*Builder) ProjectSlice

func (b *Builder) ProjectSlice(field string, limit int) *Builder

ProjectSlice projects an array slice

func (*Builder) ProjectSliceWithSkip

func (b *Builder) ProjectSliceWithSkip(field string, skip, limit int) *Builder

ProjectSliceWithSkip projects an array slice with skip

func (*Builder) Reset

func (b *Builder) Reset() *Builder

Reset clears all builder state for reuse

func (*Builder) Select

func (b *Builder) Select(fields ...string) *Builder

Select includes specific fields in the result

func (*Builder) Skip

func (b *Builder) Skip(count int64) *Builder

Skip sets the number of documents to skip

func (*Builder) String

func (b *Builder) String() string

String returns a string representation of the query

func (*Builder) ToFilter

func (b *Builder) ToFilter() bson.M

ToFilter builds a filter document for find operations

func (*Builder) ToFindOptions

func (b *Builder) ToFindOptions() *FindOptionsBuilder

ToFindOptions builds options for find operations

func (*Builder) ToJSON

func (b *Builder) ToJSON() string

ToJSON returns a JSON representation of the current query state

func (*Builder) ToPipeline

func (b *Builder) ToPipeline() []bson.M

ToPipeline builds an aggregation pipeline

func (*Builder) ToUpdateDocument

func (b *Builder) ToUpdateDocument(update bson.M) bson.M

ToUpdateDocument builds an update document

func (*Builder) Where

func (b *Builder) Where(field string, value any) *Builder

Where adds a simple equality condition

func (*Builder) WhereAnd

func (b *Builder) WhereAnd(filters ...bson.M) *Builder

WhereAnd adds an AND condition with multiple filters

func (*Builder) WhereEq

func (b *Builder) WhereEq(field string, value any) *Builder

WhereEq adds an equality condition (alias for Where)

func (*Builder) WhereExists

func (b *Builder) WhereExists(field string, exists bool) *Builder

WhereExists adds an existence check condition

func (*Builder) WhereGt

func (b *Builder) WhereGt(field string, value any) *Builder

WhereGt adds a "greater than" condition

func (*Builder) WhereGte

func (b *Builder) WhereGte(field string, value any) *Builder

WhereGte adds a "greater than or equal" condition

func (*Builder) WhereIn

func (b *Builder) WhereIn(field string, values ...any) *Builder

WhereIn adds an "in" condition

func (*Builder) WhereLt

func (b *Builder) WhereLt(field string, value any) *Builder

WhereLt adds a "less than" condition

func (*Builder) WhereLte

func (b *Builder) WhereLte(field string, value any) *Builder

WhereLte adds a "less than or equal" condition

func (*Builder) WhereNe

func (b *Builder) WhereNe(field string, value any) *Builder

WhereNe adds a "not equal" condition

func (*Builder) WhereNin

func (b *Builder) WhereNin(field string, values ...any) *Builder

WhereNin adds a "not in" condition

func (*Builder) WhereNor

func (b *Builder) WhereNor(filters ...bson.M) *Builder

WhereNor adds a NOR condition with multiple filters

func (*Builder) WhereNot

func (b *Builder) WhereNot(filter bson.M) *Builder

WhereNot adds a NOT condition

func (*Builder) WhereOr

func (b *Builder) WhereOr(filters ...bson.M) *Builder

WhereOr adds an OR condition with multiple filters

func (*Builder) WhereRegex

func (b *Builder) WhereRegex(field, pattern, options string) *Builder

WhereRegex adds a regex pattern condition

func (*Builder) WhereType

func (b *Builder) WhereType(field string, bsonType any) *Builder

WhereType adds a type check condition

func (*Builder) WithOptions

func (b *Builder) WithOptions(_ BuilderOptions) *Builder

WithOptions configures builder behavior

type BuilderOptions

type BuilderOptions struct {
	PipelineOrder []string // Order of pipeline stages: "match", "sort", "skip", "limit", "project"
}

BuilderOptions configures Builder behavior

type BuilderState

type BuilderState struct {
	Match      bson.M
	Sort       bson.D
	Skip       *int64
	Limit      *int64
	Projection bson.M
	Pipeline   []bson.M
}

BuilderState represents the internal state of a Builder for testing

type BulkWriteResult

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

BulkWriteResult wraps mongo.BulkWriteResult to implement DocumentBulkWriteResult interface

func (*BulkWriteResult) DeletedCount

func (r *BulkWriteResult) DeletedCount() int64

func (*BulkWriteResult) InsertedCount

func (r *BulkWriteResult) InsertedCount() int64

func (*BulkWriteResult) MatchedCount

func (r *BulkWriteResult) MatchedCount() int64

func (*BulkWriteResult) ModifiedCount

func (r *BulkWriteResult) ModifiedCount() int64

func (*BulkWriteResult) UpsertedCount

func (r *BulkWriteResult) UpsertedCount() int64

func (*BulkWriteResult) UpsertedIDs

func (r *BulkWriteResult) UpsertedIDs() map[int64]any

type ChangeStreamWrapper

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

ChangeStreamWrapper wraps mongo.ChangeStream to implement ChangeStream interface

func (*ChangeStreamWrapper) Close

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

func (*ChangeStreamWrapper) Decode

func (c *ChangeStreamWrapper) Decode(val any) error

func (*ChangeStreamWrapper) Err

func (c *ChangeStreamWrapper) Err() error

func (*ChangeStreamWrapper) Next

func (c *ChangeStreamWrapper) Next(ctx context.Context) bool

func (*ChangeStreamWrapper) ResumeToken

func (c *ChangeStreamWrapper) ResumeToken() bson.Raw

func (*ChangeStreamWrapper) TryNext

func (c *ChangeStreamWrapper) TryNext(ctx context.Context) bool

type Collection

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

Collection wraps a MongoDB collection to implement DocumentCollection interface

func (*Collection) Aggregate

func (c *Collection) Aggregate(ctx context.Context, pipeline any, opts *database.AggregateOptions) (database.DocumentCursor, error)

Aggregate performs aggregation on the collection

func (*Collection) BulkWrite

BulkWrite performs bulk write operations

func (*Collection) CountDocuments

func (c *Collection) CountDocuments(ctx context.Context, filter any, opts *database.CountOptions) (int64, error)

CountDocuments counts documents matching the filter

func (*Collection) CreateIndex

func (c *Collection) CreateIndex(ctx context.Context, model database.IndexModel) error

CreateIndex creates an index on the collection

func (*Collection) CreateIndexes

func (c *Collection) CreateIndexes(ctx context.Context, models []database.IndexModel) error

CreateIndexes creates multiple indexes on the collection

func (*Collection) DeleteMany

DeleteMany deletes multiple documents

func (*Collection) DeleteOne

DeleteOne deletes a single document

func (*Collection) Distinct

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

Distinct returns distinct values for a field

func (*Collection) DropIndex

func (c *Collection) DropIndex(ctx context.Context, name string) error

DropIndex drops an index from the collection

func (*Collection) EstimatedDocumentCount

func (c *Collection) EstimatedDocumentCount(ctx context.Context, opts *database.EstimatedCountOptions) (int64, error)

EstimatedDocumentCount returns an estimated count of documents in the collection

func (*Collection) Find

Find finds multiple documents

func (*Collection) FindOne

FindOne finds a single document

func (*Collection) InsertMany

func (c *Collection) InsertMany(ctx context.Context, documents []any, opts *database.InsertManyOptions) ([]any, error)

InsertMany inserts multiple documents

func (*Collection) InsertOne

func (c *Collection) InsertOne(ctx context.Context, document any, opts *database.InsertOneOptions) (any, error)

InsertOne inserts a single document

func (*Collection) ListIndexes

func (c *Collection) ListIndexes(ctx context.Context) (database.DocumentCursor, error)

ListIndexes lists all indexes on the collection

func (*Collection) ReplaceOne

func (c *Collection) ReplaceOne(ctx context.Context, filter, replacement any, opts *database.ReplaceOptions) (database.DocumentUpdateResult, error)

ReplaceOne replaces a single document

func (*Collection) UpdateMany

func (c *Collection) UpdateMany(ctx context.Context, filter, update any, opts *database.UpdateOptions) (database.DocumentUpdateResult, error)

UpdateMany updates multiple documents

func (*Collection) UpdateOne

func (c *Collection) UpdateOne(ctx context.Context, filter, update any, opts *database.UpdateOptions) (database.DocumentUpdateResult, error)

UpdateOne updates a single document

func (*Collection) Watch

Watch creates a change stream for the collection

type Connection

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

Connection implements the database.Interface for MongoDB

func (*Connection) Aggregate

func (c *Connection) Aggregate(ctx context.Context, collection string, pipeline any, opts *database.AggregateOptions) (database.DocumentCursor, error)

Aggregate performs aggregation on the specified collection

func (*Connection) Begin

func (c *Connection) Begin(ctx context.Context) (database.Tx, error)

Begin starts a MongoDB transaction

func (*Connection) BeginTx

func (c *Connection) BeginTx(ctx context.Context, opts *sql.TxOptions) (database.Tx, error)

BeginTx starts a MongoDB transaction with options

func (*Connection) Close

func (c *Connection) Close() error

Close closes the MongoDB connection

func (*Connection) Collection

func (c *Connection) Collection(name string) database.DocumentCollection

Collection returns a DocumentCollection for the specified collection name

func (*Connection) CreateCollection

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

CreateCollection creates a new collection with the specified options

func (*Connection) CreateIndex

func (c *Connection) CreateIndex(ctx context.Context, collection string, model database.IndexModel) error

CreateIndex creates an index on the specified collection

func (*Connection) CreateMigrationTable

func (c *Connection) CreateMigrationTable(ctx context.Context) error

CreateMigrationTable creates the migration collection if it doesn't exist

func (*Connection) DatabaseType

func (c *Connection) DatabaseType() string

DatabaseType returns the database type

func (*Connection) DropCollection

func (c *Connection) DropCollection(ctx context.Context, name string) error

DropCollection drops the specified collection

func (*Connection) DropIndex

func (c *Connection) DropIndex(ctx context.Context, collection, name string) error

DropIndex drops an index from the specified collection

func (*Connection) Exec

func (c *Connection) Exec(_ context.Context, _ string, _ ...any) (sql.Result, error)

Exec executes a MongoDB command (not applicable for document databases)

func (*Connection) GetClient

func (c *Connection) GetClient() *mongo.Client

GetClient returns the underlying MongoDB client instance

func (*Connection) GetDatabase

func (c *Connection) GetDatabase() *mongo.Database

GetDatabase returns the underlying MongoDB database instance

func (*Connection) GetMigrationTable

func (c *Connection) GetMigrationTable() string

GetMigrationTable returns the migration collection name for MongoDB

func (*Connection) Health

func (c *Connection) Health(ctx context.Context) error

Health checks MongoDB connection health

func (*Connection) ListIndexes

func (c *Connection) ListIndexes(ctx context.Context, collection string) ([]database.IndexModel, error)

ListIndexes lists all indexes on the specified collection

func (*Connection) Prepare

func (c *Connection) Prepare(_ context.Context, _ string) (database.Statement, error)

Prepare creates a prepared statement (not applicable for MongoDB)

func (*Connection) Query

func (c *Connection) Query(_ context.Context, _ string, _ ...any) (*sql.Rows, error)

Query executes a MongoDB query (not applicable for document databases)

func (*Connection) QueryRow

func (c *Connection) QueryRow(_ context.Context, _ string, _ ...any) types.Row

QueryRow executes a MongoDB query returning a single row (not applicable)

func (*Connection) RunCommand

func (c *Connection) RunCommand(ctx context.Context, command any) database.DocumentResult

RunCommand executes a database command

func (*Connection) Stats

func (c *Connection) Stats() (map[string]any, error)

Stats returns MongoDB connection statistics

type ConnectionBuilder

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

ConnectionBuilder helps build MongoDB client options step by step

type Cursor

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

Cursor wraps mongo.Cursor to implement DocumentCursor interface

func (*Cursor) All

func (c *Cursor) All(ctx context.Context, results any) error

func (*Cursor) Close

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

func (*Cursor) Current

func (c *Cursor) Current() bson.Raw

func (*Cursor) Decode

func (c *Cursor) Decode(val any) error

func (*Cursor) Err

func (c *Cursor) Err() error

func (*Cursor) ID

func (c *Cursor) ID() int64

func (*Cursor) Next

func (c *Cursor) Next(ctx context.Context) bool

func (*Cursor) TryNext

func (c *Cursor) TryNext(ctx context.Context) bool

type DeleteManyModel

type DeleteManyModel struct {
	Filter any
}

func (*DeleteManyModel) GetModel

func (m *DeleteManyModel) GetModel() any

type DeleteOneModel

type DeleteOneModel struct {
	Filter any
}

func (*DeleteOneModel) GetModel

func (m *DeleteOneModel) GetModel() any

type DeleteResult

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

DeleteResult wraps mongo.DeleteResult to implement DocumentDeleteResult interface

func (*DeleteResult) DeletedCount

func (r *DeleteResult) DeletedCount() int64

type FindOptionsBuilder

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

FindOptionsBuilder helps build find options

func (*FindOptionsBuilder) Build

Build builds the find options for the database package

func (*FindOptionsBuilder) Limit

func (f *FindOptionsBuilder) Limit(limit int64) *FindOptionsBuilder

Limit sets the limit option

func (*FindOptionsBuilder) Projection

func (f *FindOptionsBuilder) Projection(projection any) *FindOptionsBuilder

Projection sets the projection option

func (*FindOptionsBuilder) Skip

Skip sets the skip option

func (*FindOptionsBuilder) Sort

func (f *FindOptionsBuilder) Sort(sort any) *FindOptionsBuilder

Sort sets the sort option

type InsertOneModel

type InsertOneModel struct {
	Document any
}

WriteModel implementations for common write operations

func (*InsertOneModel) GetModel

func (m *InsertOneModel) GetModel() any

type ReplaceOneModel

type ReplaceOneModel struct {
	Filter      any
	Replacement any
	Upsert      *bool
}

func (*ReplaceOneModel) GetModel

func (m *ReplaceOneModel) GetModel() any

type SingleResult

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

SingleResult wraps mongo.SingleResult to implement DocumentResult interface

func (*SingleResult) Decode

func (r *SingleResult) Decode(v any) error

func (*SingleResult) Err

func (r *SingleResult) Err() error

type Transaction

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

Transaction implements the database.Tx interface for MongoDB

func (*Transaction) Commit

func (t *Transaction) Commit() error

Commit commits the MongoDB transaction

func (*Transaction) Exec

func (t *Transaction) Exec(_ context.Context, _ string, _ ...any) (sql.Result, error)

Exec executes a command within the transaction (not applicable for MongoDB)

func (*Transaction) GetDatabase

func (t *Transaction) GetDatabase() *mongo.Database

GetDatabase returns the database instance for use within the transaction

func (*Transaction) GetSession

func (t *Transaction) GetSession() mongo.Session

GetSession returns the underlying MongoDB session for document operations

func (*Transaction) Prepare

Prepare creates a prepared statement within the transaction (not applicable)

func (*Transaction) Query

func (t *Transaction) Query(_ context.Context, _ string, _ ...any) (*sql.Rows, error)

Query executes a query within the transaction (not applicable for MongoDB)

func (*Transaction) QueryRow

func (t *Transaction) QueryRow(_ context.Context, _ string, _ ...any) types.Row

QueryRow executes a query returning a single row within the transaction (not applicable)

func (*Transaction) Rollback

func (t *Transaction) Rollback() error

Rollback rolls back the MongoDB transaction

type UpdateManyModel

type UpdateManyModel struct {
	Filter any
	Update any
	Upsert *bool
}

func (*UpdateManyModel) GetModel

func (m *UpdateManyModel) GetModel() any

type UpdateOneModel

type UpdateOneModel struct {
	Filter any
	Update any
	Upsert *bool
}

func (*UpdateOneModel) GetModel

func (m *UpdateOneModel) GetModel() any

type UpdateResult

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

UpdateResult wraps mongo.UpdateResult to implement DocumentUpdateResult interface

func (*UpdateResult) MatchedCount

func (r *UpdateResult) MatchedCount() int64

func (*UpdateResult) ModifiedCount

func (r *UpdateResult) ModifiedCount() int64

func (*UpdateResult) UpsertedCount

func (r *UpdateResult) UpsertedCount() int64

func (*UpdateResult) UpsertedID

func (r *UpdateResult) UpsertedID() any

Jump to

Keyboard shortcuts

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