mongodriver

package module
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2026 License: MIT Imports: 13 Imported by: 23

Documentation

Overview

Package mongodriver implements a MongoDB driver for the Grove ORM.

Unlike the SQL-based drivers (pgdriver, mysqldriver), this driver uses MongoDB-native BSON operations (Find, InsertOne, UpdateOne, DeleteOne, Aggregate) instead of SQL query builders. It implements grove.GroveDriver and the adapter interfaces (txBeginner, queryBuilder) so that it integrates with the top-level grove.DB handle.

Usage:

mdb := mongodriver.New()
err := mdb.Open(ctx, "mongodb://localhost:27017/mydb")
db, err := grove.Open(mdb)

// Typed access via Unwrap:
mongo := mongodriver.Unwrap(db)
mongo.NewFind(&users).Filter(bson.M{"role": "admin"}).Scan(ctx)

Index

Constants

This section is empty.

Variables

View Source
var ErrLastInsertIDNotSupported = errors.New("mongodriver: LastInsertId is not supported; use InsertedID() instead")

ErrLastInsertIDNotSupported is returned by mongoResult.LastInsertId because MongoDB does not use auto-incrementing integer IDs by default. Use the InsertedID field to get the generated ObjectID instead.

View Source
var ErrNotSupported = errors.New("mongodriver: operation not supported")

ErrNotSupported is returned for operations that are not applicable to MongoDB.

Functions

func DateTimeFromTime

func DateTimeFromTime(t time.Time) bson.DateTime

DateTimeFromTime converts a Go time.Time to a bson.DateTime.

func IsValidObjectID

func IsValidObjectID(s string) bool

IsValidObjectID returns true if the hex string is a valid 24-character ObjectID.

func NowDateTime

func NowDateTime() bson.DateTime

NowDateTime returns the current time as a bson.DateTime.

Types

type A

type A = bson.A

A is an ordered representation of a BSON array.

type AggregateQuery

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

AggregateQuery builds and executes MongoDB aggregation pipelines. Use MongoDB.NewAggregate() to create one.

func (*AggregateQuery) GetCollection

func (q *AggregateQuery) GetCollection() string

GetCollection returns the collection name. Useful for testing.

func (*AggregateQuery) GetPipeline

func (q *AggregateQuery) GetPipeline() bson.A

GetPipeline returns the current aggregation pipeline. Useful for testing.

func (*AggregateQuery) Group

func (q *AggregateQuery) Group(group bson.M) *AggregateQuery

Group adds a $group stage to the pipeline.

func (*AggregateQuery) Limit

func (q *AggregateQuery) Limit(n int64) *AggregateQuery

Limit adds a $limit stage to the pipeline.

func (*AggregateQuery) Lookup

func (q *AggregateQuery) Lookup(lookup bson.M) *AggregateQuery

Lookup adds a $lookup stage to the pipeline.

func (*AggregateQuery) Match

func (q *AggregateQuery) Match(filter bson.M) *AggregateQuery

Match adds a $match stage to the pipeline.

func (*AggregateQuery) Project

func (q *AggregateQuery) Project(projection bson.M) *AggregateQuery

Project adds a $project stage to the pipeline.

func (*AggregateQuery) Scan

func (q *AggregateQuery) Scan(ctx context.Context, dest any) error

Scan executes the aggregation pipeline and decodes results into dest. dest should be a pointer to a slice.

func (*AggregateQuery) Skip

func (q *AggregateQuery) Skip(n int64) *AggregateQuery

Skip adds a $skip stage to the pipeline.

func (*AggregateQuery) Sort

func (q *AggregateQuery) Sort(sort bson.D) *AggregateQuery

Sort adds a $sort stage to the pipeline.

func (*AggregateQuery) Stage

func (q *AggregateQuery) Stage(stage bson.M) *AggregateQuery

Stage adds a custom pipeline stage. Use this for stages not covered by the convenience methods (e.g., $addFields, $bucket, etc.).

func (*AggregateQuery) Unwind

func (q *AggregateQuery) Unwind(path string) *AggregateQuery

Unwind adds a $unwind stage to the pipeline.

type CreateCollectionQuery

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

CreateCollectionQuery builds and executes a MongoDB createCollection command with optional $jsonSchema validation derived from a Grove model.

func (*CreateCollectionQuery) AdditionalProperties

func (q *CreateCollectionQuery) AdditionalProperties(allow bool) *CreateCollectionQuery

AdditionalProperties controls whether documents may contain fields not defined in the schema. Default is unset (MongoDB default: true).

func (*CreateCollectionQuery) BuildSchema

func (q *CreateCollectionQuery) BuildSchema() (bson.M, error)

BuildSchema generates the $jsonSchema document without executing. Useful for inspecting or logging the generated schema.

func (*CreateCollectionQuery) Collection

func (q *CreateCollectionQuery) Collection(name string) *CreateCollectionQuery

Collection overrides the collection name derived from the model.

func (*CreateCollectionQuery) Exec

Exec creates the collection with the generated $jsonSchema validator.

func (*CreateCollectionQuery) GetCollection

func (q *CreateCollectionQuery) GetCollection() string

GetCollection returns the collection name. Useful for testing.

func (*CreateCollectionQuery) IfNotExists

func (q *CreateCollectionQuery) IfNotExists() *CreateCollectionQuery

IfNotExists makes the operation a no-op if the collection already exists.

func (*CreateCollectionQuery) ValidationAction

func (q *CreateCollectionQuery) ValidationAction(action string) *CreateCollectionQuery

ValidationAction sets what happens when validation fails: "error" or "warn". Default is "error".

func (*CreateCollectionQuery) ValidationLevel

func (q *CreateCollectionQuery) ValidationLevel(level string) *CreateCollectionQuery

ValidationLevel sets the validation level: "strict", "moderate", or "off". Default is "strict".

type D

type D = bson.D

D is an ordered representation of a BSON document.

type DeleteQuery

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

DeleteQuery builds and executes MongoDB delete operations. Use MongoDB.NewDelete() to create one.

func (*DeleteQuery) Collection

func (q *DeleteQuery) Collection(name string) *DeleteQuery

Collection overrides the collection name derived from the model.

func (*DeleteQuery) Exec

func (q *DeleteQuery) Exec(ctx context.Context) (*mongoResult, error)

Exec executes the delete operation.

func (*DeleteQuery) Filter

func (q *DeleteQuery) Filter(f bson.M) *DeleteQuery

Filter sets the query filter for matching documents to delete.

func (*DeleteQuery) GetCollection

func (q *DeleteQuery) GetCollection() string

GetCollection returns the collection name. Useful for testing.

func (*DeleteQuery) GetFilter

func (q *DeleteQuery) GetFilter() bson.M

GetFilter returns the current filter. Useful for testing.

func (*DeleteQuery) IsMany

func (q *DeleteQuery) IsMany() bool

IsMany returns whether the query targets multiple documents. Useful for testing.

func (*DeleteQuery) Many

func (q *DeleteQuery) Many() *DeleteQuery

Many configures the query to delete all matching documents instead of just the first one.

type DropCollectionQuery

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

DropCollectionQuery drops a MongoDB collection.

func (*DropCollectionQuery) Collection

func (q *DropCollectionQuery) Collection(name string) *DropCollectionQuery

Collection overrides the collection name derived from the model.

func (*DropCollectionQuery) Exec

Exec drops the collection.

func (*DropCollectionQuery) GetCollection

func (q *DropCollectionQuery) GetCollection() string

GetCollection returns the collection name. Useful for testing.

type E

type E = bson.E

E is a single element inside a D.

type FindQuery

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

FindQuery builds and executes MongoDB find operations. Use MongoDB.NewFind() to create one.

func (*FindQuery) Collection

func (q *FindQuery) Collection(name string) *FindQuery

Collection overrides the collection name derived from the model.

func (*FindQuery) Count

func (q *FindQuery) Count(ctx context.Context) (int64, error)

Count returns the number of documents matching the filter.

func (*FindQuery) Filter

func (q *FindQuery) Filter(f bson.M) *FindQuery

Filter sets the query filter. Multiple calls merge filters with $and semantics.

func (*FindQuery) GetCollection

func (q *FindQuery) GetCollection() string

GetCollection returns the collection name. Useful for testing.

func (*FindQuery) GetFilter

func (q *FindQuery) GetFilter() bson.M

GetFilter returns the current filter document. Useful for testing.

func (*FindQuery) GetLimit

func (q *FindQuery) GetLimit() int64

GetLimit returns the current limit. Useful for testing.

func (*FindQuery) GetProjection

func (q *FindQuery) GetProjection() bson.M

GetProjection returns the current projection document. Useful for testing.

func (*FindQuery) GetSkip

func (q *FindQuery) GetSkip() int64

GetSkip returns the current skip. Useful for testing.

func (*FindQuery) GetSort

func (q *FindQuery) GetSort() bson.D

GetSort returns the current sort document. Useful for testing.

func (*FindQuery) Limit

func (q *FindQuery) Limit(n int64) *FindQuery

Limit sets the maximum number of documents to return.

func (*FindQuery) Project

func (q *FindQuery) Project(p bson.M) *FindQuery

Project sets the projection (which fields to include/exclude).

func (*FindQuery) Scan

func (q *FindQuery) Scan(ctx context.Context) error

Scan executes the find query and decodes results into the model. For slice pointers, it decodes all matching documents. For struct pointers, it decodes the first matching document.

func (*FindQuery) Skip

func (q *FindQuery) Skip(n int64) *FindQuery

Skip sets the number of documents to skip before returning results.

func (*FindQuery) Sort

func (q *FindQuery) Sort(s bson.D) *FindQuery

Sort sets the sort order. Example: bson.D{{"name", 1}, {"created_at", -1}}

type InsertQuery

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

InsertQuery builds and executes MongoDB insert operations. Use MongoDB.NewInsert() to create one.

func (*InsertQuery) BuildDoc

func (q *InsertQuery) BuildDoc() (bson.M, error)

buildDoc converts the model to a BSON document for insertion. Exported for testing purposes.

func (*InsertQuery) BuildDocs

func (q *InsertQuery) BuildDocs() ([]bson.M, error)

buildDocs converts a slice model to BSON documents for insertion. Exported for testing purposes.

func (*InsertQuery) Collection

func (q *InsertQuery) Collection(name string) *InsertQuery

Collection overrides the collection name derived from the model.

func (*InsertQuery) Exec

func (q *InsertQuery) Exec(ctx context.Context) (*mongoResult, error)

Exec executes the insert operation. For single documents, uses InsertOne. For slices, uses InsertMany.

func (*InsertQuery) GetCollection

func (q *InsertQuery) GetCollection() string

GetCollection returns the collection name. Useful for testing.

type M

type M = bson.M

M is an unordered map representation of a BSON document.

type MongoDB

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

MongoDB implements grove.GroveDriver for MongoDB using the official Go MongoDB driver v2. It also implements the grove adapter interfaces (txBeginner, queryBuilder) for integration with grove.DB.

func New

func New() *MongoDB

New creates a new unconnected MongoDB driver. Call Open to establish a connection to the MongoDB server.

func Unwrap

func Unwrap(db *grove.DB) *MongoDB

Unwrap extracts the underlying *MongoDB from a *grove.DB handle. This allows access to MongoDB-specific query builders and features.

mdb := mongodriver.Unwrap(db) // returns *mongodriver.MongoDB
mdb.NewFind(&users).Filter(bson.M{"role": "admin"}).Scan(ctx)

Panics if the driver is not a *MongoDB.

func (*MongoDB) Client

func (db *MongoDB) Client() *mongo.Client

Client returns the underlying mongo.Client.

func (*MongoDB) Close

func (db *MongoDB) Close() error

Close disconnects from the MongoDB server.

func (*MongoDB) Collection

func (db *MongoDB) Collection(name string) *mongo.Collection

Collection returns a mongo.Collection handle for the named collection.

func (*MongoDB) Database

func (db *MongoDB) Database() *mongo.Database

Database returns the underlying mongo.Database.

func (*MongoDB) DatabaseName

func (db *MongoDB) DatabaseName() string

DatabaseName returns the database name.

func (*MongoDB) GroveDelete

func (db *MongoDB) GroveDelete(model any) any

GroveDelete is the adapter method for grove.DB.NewDelete().

func (*MongoDB) GroveInsert

func (db *MongoDB) GroveInsert(model any) any

GroveInsert is the adapter method for grove.DB.NewInsert().

func (*MongoDB) GroveSelect

func (db *MongoDB) GroveSelect(model ...any) any

GroveSelect is the adapter method for grove.DB.NewSelect().

func (*MongoDB) GroveTx

func (db *MongoDB) GroveTx(ctx context.Context, isolationLevel int, readOnly bool) (any, error)

GroveTx starts a MongoDB session-based transaction. This is the adapter method for grove.DB.BeginTx().

func (*MongoDB) GroveUpdate

func (db *MongoDB) GroveUpdate(model any) any

GroveUpdate is the adapter method for grove.DB.NewUpdate().

func (*MongoDB) Name

func (db *MongoDB) Name() string

Name returns the driver identifier.

func (*MongoDB) NewAggregate

func (db *MongoDB) NewAggregate(collection string) *AggregateQuery

NewAggregate creates a new aggregation pipeline query for the given collection.

func (*MongoDB) NewCreateCollection

func (db *MongoDB) NewCreateCollection(model any) *CreateCollectionQuery

NewCreateCollection creates a CreateCollectionQuery for the given model.

mdb.NewCreateCollection((*User)(nil)).
    ValidationLevel("strict").
    ValidationAction("error").
    AdditionalProperties(false).
    IfNotExists().
    Exec(ctx)

func (*MongoDB) NewDelete

func (db *MongoDB) NewDelete(model any) *DeleteQuery

NewDelete creates a new DeleteQuery.

func (*MongoDB) NewDropCollection

func (db *MongoDB) NewDropCollection(model any) *DropCollectionQuery

NewDropCollection creates a DropCollectionQuery for the given model.

mdb.NewDropCollection((*User)(nil)).Exec(ctx)

func (*MongoDB) NewFind

func (db *MongoDB) NewFind(model ...any) *FindQuery

NewFind creates a new FindQuery. model can be:

  • *[]User (slice pointer for multi-row)
  • *User (struct pointer for single row)
  • (*User)(nil) (nil pointer for collection reference without binding)

func (*MongoDB) NewInsert

func (db *MongoDB) NewInsert(model any) *InsertQuery

NewInsert creates a new InsertQuery. model can be a struct pointer or a pointer to a slice (for bulk insert).

func (*MongoDB) NewUpdate

func (db *MongoDB) NewUpdate(model any) *UpdateQuery

NewUpdate creates a new UpdateQuery.

func (*MongoDB) Open

func (db *MongoDB) Open(ctx context.Context, uri string, opts ...MongoOption) error

Open connects to MongoDB using the given URI. The database name is extracted from the URI path. Use WithDatabase to override.

mdb := mongodriver.New()
err := mdb.Open(ctx, "mongodb://localhost:27017/mydb")

func (*MongoDB) Ping

func (db *MongoDB) Ping(ctx context.Context) error

Ping verifies that the MongoDB server is reachable.

func (*MongoDB) SetHooks

func (db *MongoDB) SetHooks(engine *hook.Engine)

SetHooks attaches a hook engine for lifecycle hooks.

type MongoOption

type MongoOption func(*mongoOptions)

MongoOption configures the MongoDB driver during Open.

func WithConnectTimeout

func WithConnectTimeout(d time.Duration) MongoOption

WithConnectTimeout overrides the default TCP connect timeout.

func WithDatabase

func WithDatabase(name string) MongoOption

WithDatabase overrides the database name extracted from the connection URI. If not set, the database name from the URI is used.

func WithMaxConnIdleTime

func WithMaxConnIdleTime(d time.Duration) MongoOption

WithMaxConnIdleTime sets how long an idle pooled connection lives.

func WithMaxConnecting

func WithMaxConnecting(n uint64) MongoOption

WithMaxConnecting caps concurrent connection establishment.

func WithMaxPoolSize

func WithMaxPoolSize(n uint64) MongoOption

WithMaxPoolSize caps the pooled connection count.

func WithMinPoolSize

func WithMinPoolSize(n uint64) MongoOption

WithMinPoolSize keeps n connections warm in the pool. Use for polling workloads (e.g. dispatch dequeue loops) to avoid socket churn.

func WithPingRetries

func WithPingRetries(n int) MongoOption

WithPingRetries sets the number of additional ping attempts after the first failure during Open. Use 0 to disable retries.

func WithPingRetryBackoff

func WithPingRetryBackoff(d time.Duration) MongoOption

WithPingRetryBackoff sets the base backoff between ping attempts. The effective delay grows exponentially and is capped at 5s.

func WithPingTimeout

func WithPingTimeout(d time.Duration) MongoOption

WithPingTimeout overrides the per-attempt ping timeout used during Open.

func WithServerSelectionTimeout

func WithServerSelectionTimeout(d time.Duration) MongoOption

WithServerSelectionTimeout overrides the default server-selection timeout.

func WithSkipPing

func WithSkipPing(skip bool) MongoOption

WithSkipPing disables the initial connectivity check during Open. Useful when the caller prefers to defer connectivity verification to Health().

func WithTimeout

func WithTimeout(d time.Duration) MongoOption

WithTimeout sets the mongo v2 unified per-operation timeout. A zero value leaves the driver default in place.

type MongoTx

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

MongoTx wraps a MongoDB session with an active transaction. Query builder methods on MongoTx execute within the transaction's session context.

func (*MongoTx) Commit

func (tx *MongoTx) Commit() error

Commit commits the transaction and ends the session.

func (*MongoTx) DB

func (tx *MongoTx) DB() *MongoDB

DB returns the parent MongoDB driver.

func (*MongoTx) NewDelete

func (tx *MongoTx) NewDelete(model any) *DeleteQuery

NewDelete creates a DeleteQuery that executes within this transaction.

func (*MongoTx) NewFind

func (tx *MongoTx) NewFind(model ...any) *FindQuery

NewFind creates a FindQuery that executes within this transaction.

func (*MongoTx) NewInsert

func (tx *MongoTx) NewInsert(model any) *InsertQuery

NewInsert creates an InsertQuery that executes within this transaction.

func (*MongoTx) NewUpdate

func (tx *MongoTx) NewUpdate(model any) *UpdateQuery

NewUpdate creates an UpdateQuery that executes within this transaction.

func (*MongoTx) Rollback

func (tx *MongoTx) Rollback() error

Rollback aborts the transaction and ends the session.

func (*MongoTx) Session

func (tx *MongoTx) Session() *mongo.Session

Session returns the underlying MongoDB session.

func (*MongoTx) SessionContext

func (tx *MongoTx) SessionContext(ctx context.Context) context.Context

SessionContext returns a context with the session attached, suitable for passing to MongoDB operations that should participate in the transaction.

type ObjectID

type ObjectID = bson.ObjectID

ObjectID is the MongoDB 12-byte unique identifier.

var NilObjectID ObjectID

NilObjectID is the zero value for ObjectID.

func NewObjectID

func NewObjectID() ObjectID

NewObjectID generates a new ObjectID.

func ObjectIDFromHex

func ObjectIDFromHex(s string) (ObjectID, error)

ObjectIDFromHex creates an ObjectID from a hex string.

type Timestamp

type Timestamp = bson.DateTime

Timestamp is a convenience wrapper around time.Time for BSON date fields.

type UpdateQuery

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

UpdateQuery builds and executes MongoDB update operations. Use MongoDB.NewUpdate() to create one.

func (*UpdateQuery) Collection

func (q *UpdateQuery) Collection(name string) *UpdateQuery

Collection overrides the collection name derived from the model.

func (*UpdateQuery) Exec

func (q *UpdateQuery) Exec(ctx context.Context) (*mongoResult, error)

Exec executes the update operation.

func (*UpdateQuery) Filter

func (q *UpdateQuery) Filter(f bson.M) *UpdateQuery

Filter sets the query filter for matching documents to update.

func (*UpdateQuery) GetCollection

func (q *UpdateQuery) GetCollection() string

GetCollection returns the collection name. Useful for testing.

func (*UpdateQuery) GetFilter

func (q *UpdateQuery) GetFilter() bson.M

GetFilter returns the current filter. Useful for testing.

func (*UpdateQuery) GetUpdate

func (q *UpdateQuery) GetUpdate() bson.M

GetUpdate returns the current update document. Useful for testing.

func (*UpdateQuery) IsMany

func (q *UpdateQuery) IsMany() bool

IsMany returns whether the query targets multiple documents. Useful for testing.

func (*UpdateQuery) IsUpsert

func (q *UpdateQuery) IsUpsert() bool

IsUpsert returns whether upsert is enabled. Useful for testing.

func (*UpdateQuery) Many

func (q *UpdateQuery) Many() *UpdateQuery

Many configures the query to update all matching documents instead of just the first one.

func (*UpdateQuery) Set

func (q *UpdateQuery) Set(field string, value any) *UpdateQuery

Set adds a field to the $set update operator.

func (*UpdateQuery) SetUpdate

func (q *UpdateQuery) SetUpdate(update bson.M) *UpdateQuery

SetUpdate sets the entire update document (replaces any previous $set calls). Use this for complex update operations like $inc, $push, $unset, etc.

func (*UpdateQuery) Upsert

func (q *UpdateQuery) Upsert() *UpdateQuery

Upsert enables upsert behavior: if no document matches the filter, a new document is inserted.

Directories

Path Synopsis
Package mongomigrate provides a MongoDB-specific migration executor for the Grove migration system.
Package mongomigrate provides a MongoDB-specific migration executor for the Grove migration system.

Jump to

Keyboard shortcuts

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