mgo

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 8, 2026 License: Apache-2.0 Imports: 23 Imported by: 3

README

MongoDB Abstraction Layer (db/mgo)

db/mgo is a high-level Go package designed to simplify interactions with MongoDB. It acts as a thoughtful wrapper around the official MongoDB Go Driver, providing a streamlined and opinionated approach to common database operations.

Core Philosophy

The primary goal of this package is to promote a consistent, maintainable, and self-describing data access layer. It achieves this through:

  • Singleton Connection Management: Ensures a single, efficiently managed database connection for the entire application.
  • Standardized Document Interface (DocInter): Mandates that all data models define their own collection name, validation rules, and database indexes.
  • Automated Schema Management: Automatically creates collections and indexes based on model definitions, reducing manual setup and preventing configuration drift.
  • Decoupled Schema Definition: Encourages separating the collection's schema (name, indexes) from the model's data structure, promoting cleaner code.

Key Features

  • Singleton Connection: Uses sync.Once to guarantee a single, thread-safe database connection.
  • Functional Options: Provides a clean, flexible API for configuring the database connection and for constructing model instances.
  • Self-Describing Models: The DocInter and Index interfaces encourage models to be self-contained and aware of their database schema.
  • Automatic Index Creation: On application startup, automatically creates necessary indexes for collections that don't yet exist.
  • Fluent Bulk Operations: Provides a BulkOperation builder for safely and efficiently executing multiple insert, update, or delete operations in a single request.

How to Use

This guide demonstrates the recommended pattern for defining a model, its schema, and performing database operations.

1. Define Your Model and Schema

Create your data model and its corresponding schema definition. The schema should define the collection name and indexes. Use an init() function to automatically register this schema.

The model itself should embed the mgo.Index interface, which will be fulfilled by injecting the schema definition during instantiation.

models/user.go

package models

import (
	"github.com/94peter/vulpes/db/mgo"
	"github.com/94peter/vulpes/validate"
	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

// userCollection defines the schema for the "users" collection.
// It uses NewCollectDef to create a reusable, self-contained schema definition.
var userCollection = mgo.NewCollectDef("users", func() []mongo.IndexModel {
	return []mongo.IndexModel{
		{
			Keys:    bson.D{{Key: "email", Value: 1}},
			Options: options.Index().SetUnique(true),
		},
	}
})

// init automatically registers the User model's indexes when the package is imported.
func init() {
	mgo.RegisterIndex(userCollection)
}

// User represents the data structure for a user document.
type User struct {
	mgo.Index   `bson:"-"` // Embed the Index interface, ignored by BSON marshalling.
	ID        bson.ObjectID `bson:"_id,omitempty"`
	Name      string        `bson:"name" validate:"required"
	Email     string        `bson:"email" validate:"required,email"
}

// Validate implements the validation logic for a User.
func (u *User) Validate() error {
	return validate.Struct(u)
}

// userOption defines the functional option type for creating a User.
type userOption func(*User)

// NewUser is a constructor that creates a new User instance with the given options.
// It injects the collection schema and sets default values.
func NewUser(opts ...userOption) *User {
	u := &User{
		Index: userCollection, // Inject the collection definition.
		ID:    bson.NewObjectID(),
	}
	for _, opt := range opts {
		opt(u)
	}
	return u
}

// WithUserName is a functional option to set the user's name.
func WithUserName(name string) userOption {
	return func(u *User) {
		u.Name = name
	}
}

// WithUserEmail is a functional option to set the user's email.
func WithUserEmail(email string) userOption {
	return func(u *User) {
		u.Email = email
	}
}
2. Initialize and Use in main.go

In your application's entry point, initialize the database connection. Use the model's constructor (NewUser) to create new instances safely.

main.go

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/94peter/vulpes/db/mgo"
	// Blank import to trigger the init() function in the models package.
	_ "path/to/your/models"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()

	// 1. Initialize the singleton MongoDB connection.
	err := mgo.InitConnection(
		ctx,
		"myAppDatabase", // The name of your database
		mgo.WithURI("mongodb://localhost:27017"),
		mgo.WithMaxPoolSize(20),
	)
	if err != nil {
		log.Fatalf("Failed to connect to MongoDB: %v", err)
	}
	defer mgo.Close(ctx);

	fmt.Println("Successfully connected to MongoDB.")

	// 2. Sync indexes for all registered models.
	if err := mgo.SyncIndexes(ctx); err != nil {
		log.Fatalf("Failed to sync indexes: %v", err)
	}
	fmt.Println("Indexes are up to date.")

	// 3. Example: Performing a bulk operation.
	bulkOp := mgo.NewBulkOperation("users")
	bulkOp.InsertOne(models.NewUser(
		models.WithUserName("Peter"),
		models.WithUserEmail("peter@example.com"),
	))
	bulkOp.InsertOne(models.NewUser(
		models.WithUserName("Alice"),
		models.WithUserEmail("alice@example.com"),
	))
	// You can also chain other operations like Update or Delete
	// bulkOp.UpdateById(someId, bson.D{{"$set", bson.M{{"name": "New Name"}}}})

	result, err := bulkOp.Execute(ctx)
	if err != nil {
		log.Fatalf("Bulk operation failed: %v", err)
	}
	fmt.Printf("Successfully inserted %d documents.\n", result.InsertedCount)
}

Documentation

Overview

Package mgo provides a high-level abstraction layer over the official MongoDB Go driver, simplifying connection management, document operations, and schema definitions.

Package mgo provides a high-level abstraction layer over the official MongoDB Go driver, simplifying connection management, document operations, and schema definitions.

Package mgo provides a high-level abstraction layer over the official MongoDB Go driver, simplifying connection management, document operations, and schema definitions.

Package mgo provides a high-level abstraction layer over the official MongoDB Go driver, simplifying connection management, document operations, and schema definitions.

Index

Constants

View Source
const (
	MigrateStatusPending migrateStatus = "pending"
	MigrateStatusRunning migrateStatus = "running"
	MigrateStatusSuccess migrateStatus = "success"
	MigrateStatusFailed  migrateStatus = "failed"
)

Variables

View Source
var (
	// ErrInvalidDocument is returned when a document fails validation or is otherwise malformed.
	ErrInvalidDocument = errors.New("invalid document")
	// ErrNotConnected is returned when a database operation is attempted before a connection is established.
	ErrNotConnected = errors.New("mongodb not connected")
	// ErrConnectionFailed is returned when the initial connection attempt to the MongoDB server fails.
	ErrConnectionFailed = errors.New("mongodb connection failed")
	// ErrPingFailed is returned when the client fails to ping the MongoDB server to verify the connection.
	ErrPingFailed = errors.New("mongodb ping failed")
	// ErrCreateIndexFailed is returned when an attempt to create one or more indexes fails.
	ErrCreateIndexFailed = errors.New("mongodb create index failed")
	// ErrListCollectionFailed is returned when listing the collections in the database fails.
	ErrListCollectionFailed = errors.New("mongodb list collection failed")
	// ErrWriteFailed is returned when a write operation fails.
	ErrWriteFailed = errors.New("mongodb write failed")
	// ErrReadFailed is returned when a read operation fails.
	ErrReadFailed = errors.New("mongodb read failed")

	StatusMongoDBInvalidDocument      = status.New(codes.InvalidArgument, "mongodb invalid document")
	StatusMongoDBNotConnected         = status.New(codes.Aborted, "mongodb not connected")
	StatusMongoDBConnectionFailed     = status.New(codes.Aborted, "mongodb connection failed")
	StatusMongoDBPingFailed           = status.New(codes.Aborted, "mongodb ping failed")
	StatusMongoDBCreateIndexFailed    = status.New(codes.Aborted, "mongodb create index failed")
	StatusMongoDBListCollectionFailed = status.New(codes.Aborted, "mongodb list collection failed")
	StatusMongoDBWriteFailed          = status.New(codes.Internal, "mongodb write failed")
	StatusMongoDBReadFailed           = status.New(codes.Internal, "mongodb read failed")
)

Standardized errors for the mgo package, providing consistent error types for common database operations.

Functions

func Close

func Close(ctx context.Context) error

Close gracefully disconnects the client from the MongoDB server. It should be called at the end of the application's lifecycle, for example, using defer in main.

func CountDocument

func CountDocument(ctx context.Context, collectionName string, filter any) (int64, error)

func DeleteById

func DeleteById[T DocInter](ctx context.Context, doc T) (int64, error)

DeleteById deletes a single document identified by the _id of the provided document instance. doc: An instance of the document, from which the _id is extracted for the filter.

func DeleteMany

func DeleteMany[T DocInter](ctx context.Context, doc T, filter bson.D) (int64, error)

DeleteMany deletes all documents matching the filter. doc: An instance of the document type, used to determine the collection.

func DeleteOne

func DeleteOne[T DocInter](ctx context.Context, doc T, filter bson.D) (int64, error)

DeleteOne deletes a single document matching the filter. doc: An instance of the document type, used to determine the collection.

func Distinct

func Distinct[T any](
	ctx context.Context, collectionName string, field string, filter any,
	opts ...options.Lister[options.DistinctOptions],
) ([]T, error)

func Find

func Find[T DocInter](
	ctx context.Context, doc T, filter any, limit uint16,
	opts ...options.Lister[options.FindOptions],
) ([]T, error)

func FindById

func FindById[T DocInter](ctx context.Context, doc T) error

func FindOne

func FindOne[T DocInter](
	ctx context.Context, doc T, filter any,
	opts ...options.Lister[options.FindOneOptions],
) error

func GetDatabase

func GetDatabase() *mongo.Database

func Import

func Import(
	ctx context.Context, collectionName string, reader io.Reader,
) error

func InitConnection

func InitConnection(ctx context.Context, dbName string, tracer trace.Tracer, opts ...Option) error

InitConnection establishes a connection to the MongoDB server using a singleton pattern. It is safe to call this function multiple times; the connection will only be initialized once.

ctx: A context for the connection process. dbName: The name of the database to connect to. opts: A variadic set of Option functions for configuration.

func InitTestContainer

func InitTestContainer(ctx context.Context) (drop func(), close func(), err error)

func IsCollectionExist

func IsCollectionExist(ctx context.Context, collectionName string) (bool, error)

func IsConnected

func IsConnected() bool

func IsHealth

func IsHealth(ctx context.Context) error

func NewEmptyModel

func NewEmptyModel[T DocWithInitIndex]() T

func NewErrOnFind

func NewErrOnFind(err error) func(
	_ context.Context, _ string, _ any, _ ...options.Lister[options.FindOptions],
) (*mongo.Cursor, error)

NewErrOnFind returns an OnFind function that always returns the specified error.

func NewErrOnFindOne

func NewErrOnFindOne(err error) func(
	ctx context.Context, collection string, filter any, opts ...options.Lister[options.FindOneOptions],
) *mongo.SingleResult

NewErrOnFindOne returns an OnFindOne function that returns a SingleResult containing the specified error.

func NewModelWithId

func NewModelWithId[T DocWithId](opts ...DocInterOpt) T

func NewOnBulkOperationMock

func NewOnBulkOperationMock(result *mongo.BulkWriteResult, err error) func(cname string) BulkOperator

NewOnBulkOperationMock returns an OnNewBulkOperation function that creates a mock BulkOperator. The mock BulkOperator's chainable methods are pre-configured to return itself, and its Execute method is set to return the provided result and error.

func NewOnFindMock

func NewOnFindMock(fakeData ...any) func(
	ctx context.Context, collection string, filter any, opts ...options.Lister[options.FindOptions],
) (*mongo.Cursor, error)

NewOnFindMock returns an OnFind function that returns a cursor with the given fake data.

func NewOnFindOneMock

func NewOnFindOneMock(fakeData any) func(
	ctx context.Context, collection string, filter any, opts ...options.Lister[options.FindOneOptions],
) *mongo.SingleResult

NewOnFindOneMock returns an OnFindOne function that returns a SingleResult with the given fake data.

func NewOnPipeFindMock

func NewOnPipeFindMock(fakeData ...any) func(
	_ context.Context, _ string, _ mongo.Pipeline,
) (*mongo.Cursor, error)

NewOnPipeFindMock returns an OnPipeFind function that returns a cursor with the given fake data.

func NewOnSaveMock

func NewOnSaveMock() func(ctx context.Context, doc DocInter) (DocInter, error)

NewOnSaveMock returns an OnSave function that simulates a successful save. It assigns a new ObjectID to the document and returns it.

func PipeFind

func PipeFind[T MgoAggregate](
	ctx context.Context, aggr T, filter bson.M, limit uint16,
) ([]T, error)

func PipeFindByPipeline

func PipeFindByPipeline[T any](
	ctx context.Context,
	collectionName string,
	pipeline mongo.Pipeline,
	limit uint16,
) ([]T, error)

func PipeFindOne

func PipeFindOne[T MgoAggregate](ctx context.Context, aggr T, filter bson.M) error

func RegisterIndex

func RegisterIndex(index Index)

RegisterIndex adds a new Index definition to the global registry. This is typically called from the init() function of a model package.

func ReplaceOne

func ReplaceOne[T DocInter](
	ctx context.Context, doc T, filter any,
	opts ...options.Lister[options.ReplaceOptions],
) (int64, error)

func Save

func Save[T DocInter](ctx context.Context, doc T) (T, error)

func SetDatastore

func SetDatastore(mock Datastore) (restore func())

SetDatastore replaces the default datastore with a mock for testing. It returns a function to restore the original datastore, which should be called at the end of the test using defer.

Example:

restore := SetDatastore(&MockDatastore{...})
defer restore()

func SyncIndexes

func SyncIndexes(ctx context.Context) error

SyncIndexes ensures that all registered indexes are present in the database. It iterates through all registered models and applies their index definitions. The underlying MongoDB driver's CreateMany command is idempotent: it will only create indexes that do not already exist and will not change existing ones. This is a safe and effective way to keep code-defined schemas and the database in sync.

func ToStatus

func ToStatus(err error) *status.Status

func UpdateById

func UpdateById[T DocInter](ctx context.Context, doc T, update bson.D) (int64, error)

UpdateById updates a single document identified by the _id field of the provided document instance. It offers a flexible way to apply any update operator ($set, $inc, etc.).

doc: An instance of the document, from which the _id is extracted for the filter.

It is also used to determine the target collection.

update: The update document, e.g., bson.D{{"$set", bson.D{{"field", "value"}}}}.

func UpdateMany

func UpdateMany[T DocInter](ctx context.Context, doc T, filter bson.D, update bson.D) (int64, error)

func UpdateOne

func UpdateOne[T DocInter](ctx context.Context, doc T, filter bson.D, update bson.D) (int64, error)

UpdateOne updates the first document that matches a given filter. This is a generic and flexible update function.

doc: An instance of the document type, used to determine the collection. filter: The filter to select the document to update. update: The update document, e.g., bson.D{{"$set", bson.D{{"field", "value"}}}}.

Types

type BulkOperator

type BulkOperator interface {
	InsertOne(doc DocInter) BulkOperator
	UpdateOne(filter any, update any) BulkOperator
	UpdateById(id any, update any) BulkOperator
	UpsertOne(filter any, update any) BulkOperator
	DeleteOne(filter any) BulkOperator
	DeleteById(id any) BulkOperator

	Execute(ctx context.Context) (*mongo.BulkWriteResult, error)
}

BulkOperator defines the interface for the fluent bulk operation builder.

func NewBulkOperation

func NewBulkOperation(cname string) (BulkOperator, error)

NewBulkOperation creates a new builder for a bulk operation on a specific collection. cname: The name of the collection to perform operations on.

type Datastore

type Datastore interface {
	Save(ctx context.Context, doc DocInter) (DocInter, error)
	CountDocument(
		ctx context.Context, collectionName string, filter any,
	) (int64, error)
	Find(
		ctx context.Context, collection string, filter any,
		opts ...options.Lister[options.FindOptions],
	) (*mongo.Cursor, error)
	FindOne(
		ctx context.Context, collection string, filter any,
		opts ...options.Lister[options.FindOneOptions],
	) *mongo.SingleResult
	UpdateOne(
		ctx context.Context, collection string, filter bson.D, update bson.D,
		opts ...options.Lister[options.UpdateOneOptions],
	) (int64, error)
	UpdateMany(ctx context.Context, collection string, filter bson.D, update bson.D) (int64, error)
	DeleteOne(ctx context.Context, collection string, filter bson.D) (int64, error)
	DeleteMany(ctx context.Context, collection string, filter bson.D) (int64, error)
	ReplaceOne(
		ctx context.Context, collection string, filter any, replacement any,
		opts ...options.Lister[options.ReplaceOptions],
	) (*mongo.UpdateResult, error)

	PipeFind(
		ctx context.Context, collection string, pipeline mongo.Pipeline,
	) (*mongo.Cursor, error)
	PipeFindOne(ctx context.Context, collection string, pipeline mongo.Pipeline) *mongo.SingleResult

	Distinct(
		ctx context.Context, collectionName string, field string, filter any,
		opts ...options.Lister[options.DistinctOptions],
	) ([]bson.RawValue, error)

	Import(
		ctx context.Context, collectionName string, reader io.Reader,
	) error

	NewBulkOperation(cname string) BulkOperator
	// contains filtered or unexported methods
}

Datastore defines the interface for all database operations. It allows for mocking the entire package for testing purposes.

type DocInter

type DocInter interface {
	Index
	// Validate performs business logic validation on the document's fields.
	Validate() error
	GetId() any
	SetId(any)
}

DocInter defines a standard interface for all database documents. By embedding the Index interface, it requires all documents to specify their collection name, index definitions, and validation logic. This promotes a consistent and self-describing data model.

type DocInterOpt

type DocInterOpt func(d DocInter)

func WithId

func WithId(id any) DocInterOpt

type DocWithId

type DocWithId interface {
	DocWithInitIndex
	NewId()
	DocInter
}

type DocWithInitIndex

type DocWithInitIndex interface {
	InitIndex()
}

type Index

type Index interface {
	// C returns the name of the MongoDB collection.
	C() string
	// Indexes returns a slice of mongo.IndexModel, defining the indexes for the collection.
	Indexes() []mongo.IndexModel
}

Index defines the interface for a collection's schema, including its name and index specifications. This allows for the automatic creation and registration of indexes.

func NewCollectDef

func NewCollectDef(name string, f func() []mongo.IndexModel) Index

NewCollectDef creates a new collection definition that satisfies the Index interface. This is a helper function to simplify the creation of index definitions.

type MgoAggregate

type MgoAggregate interface {
	GetPipeline(q bson.M) mongo.Pipeline
	C() string
}

type MigrationInfo

type MigrationInfo struct {
	Status  migrateStatus `bson:"status"`
	LastRun time.Time     `bson:"last_run"`
	Error   string        `bson:"error,omitempty"`
	Version int           `bson:"version"`
}

type MockBulkOperator

type MockBulkOperator struct {
	OnInsertOne func(doc DocInter) BulkOperator
	OnUpdateOne func(filter any, update any) BulkOperator
	OnUpsertOne func(filter any, update any) BulkOperator
	OnExecute   func(ctx context.Context) (*mongo.BulkWriteResult, error)
	OnDeleteOne func(filter any) BulkOperator
}

MockBulkOperator is a mock implementation of the BulkOperator interface.

func (*MockBulkOperator) DeleteById

func (m *MockBulkOperator) DeleteById(id any) BulkOperator

func (*MockBulkOperator) DeleteOne

func (m *MockBulkOperator) DeleteOne(filter any) BulkOperator

func (*MockBulkOperator) Execute

func (*MockBulkOperator) InsertOne

func (m *MockBulkOperator) InsertOne(doc DocInter) BulkOperator

func (*MockBulkOperator) UpdateById

func (m *MockBulkOperator) UpdateById(id any, update any) BulkOperator

func (*MockBulkOperator) UpdateOne

func (m *MockBulkOperator) UpdateOne(filter any, update any) BulkOperator

func (*MockBulkOperator) UpsertOne

func (m *MockBulkOperator) UpsertOne(filter any, update any) BulkOperator

type MockDatastore

type MockDatastore struct {
	OnSave          func(ctx context.Context, doc DocInter) (DocInter, error)
	OnCountDocument func(ctx context.Context, collectionName string, filter any) (int64, error)
	OnFind          func(
		ctx context.Context, collection string, filter any, opts ...options.Lister[options.FindOptions],
	) (*mongo.Cursor, error)
	OnFindOne func(
		ctx context.Context, collection string, filter any, opts ...options.Lister[options.FindOneOptions],
	) *mongo.SingleResult
	OnUpdateOne  func(ctx context.Context, collection string, filter bson.D, update bson.D) (int64, error)
	OnUpdateMany func(ctx context.Context, collection string, filter bson.D, update bson.D) (int64, error)
	OnReplaceOne func(
		ctx context.Context, collection string, filter any, replacement any, opts ...options.Lister[options.ReplaceOptions],
	) (*mongo.UpdateResult, error)
	OnDeleteOne        func(ctx context.Context, collection string, filter bson.D) (int64, error)
	OnDeleteMany       func(ctx context.Context, collection string, filter bson.D) (int64, error)
	OnPipeFind         func(ctx context.Context, collection string, pipeline mongo.Pipeline) (*mongo.Cursor, error)
	OnPipeFindOne      func(ctx context.Context, collection string, pipeline mongo.Pipeline) *mongo.SingleResult
	OnNewBulkOperation func(cname string) BulkOperator
	OnGetCollection    func(name string) *mongo.Collection
	OnGetDatabase      func() *mongo.Database
	OnClose            func(ctx context.Context) error
	OnCleanDb          func(ctx context.Context) error
	OnDistinct         func(
		ctx context.Context, collectionName string, field string, filter any, opts ...options.Lister[options.DistinctOptions],
	) ([]bson.RawValue, error)
	OnStartTraceSpan func(
		ctx context.Context, collectionName string, operation string, statement any,
	) (context.Context, trace.Span)
	OnImport func(ctx context.Context, collectionName string, reader io.Reader) error
}

MockDatastore is a mock implementation of the Datastore interface. It allows for setting mock functions for each method, making it easy to control the behavior of the datastore in tests.

func (*MockDatastore) CountDocument

func (m *MockDatastore) CountDocument(ctx context.Context, collectionName string, filter any) (int64, error)

func (*MockDatastore) DeleteMany

func (m *MockDatastore) DeleteMany(ctx context.Context, collection string, filter bson.D) (int64, error)

func (*MockDatastore) DeleteOne

func (m *MockDatastore) DeleteOne(ctx context.Context, collection string, filter bson.D) (int64, error)

func (*MockDatastore) Distinct

func (m *MockDatastore) Distinct(
	ctx context.Context, collectionName string, field string, filter any, opts ...options.Lister[options.DistinctOptions],
) ([]bson.RawValue, error)

Interface implementations for MockDatastore

func (*MockDatastore) Find

func (m *MockDatastore) Find(
	ctx context.Context, collection string, filter any, opts ...options.Lister[options.FindOptions],
) (*mongo.Cursor, error)

func (*MockDatastore) FindOne

func (m *MockDatastore) FindOne(
	ctx context.Context, collection string, filter any, opts ...options.Lister[options.FindOneOptions],
) *mongo.SingleResult

func (*MockDatastore) Import

func (m *MockDatastore) Import(ctx context.Context, collectionName string, reader io.Reader) error

func (*MockDatastore) NewBulkOperation

func (m *MockDatastore) NewBulkOperation(cname string) BulkOperator

func (*MockDatastore) PipeFind

func (m *MockDatastore) PipeFind(
	ctx context.Context, collection string, pipeline mongo.Pipeline,
) (*mongo.Cursor, error)

func (*MockDatastore) PipeFindOne

func (m *MockDatastore) PipeFindOne(
	ctx context.Context, collection string, pipeline mongo.Pipeline,
) *mongo.SingleResult

func (*MockDatastore) ReplaceOne

func (m *MockDatastore) ReplaceOne(
	ctx context.Context,
	collection string,
	filter any,
	replacement any,
	opts ...options.Lister[options.ReplaceOptions],
) (*mongo.UpdateResult, error)

func (*MockDatastore) Save

func (m *MockDatastore) Save(ctx context.Context, doc DocInter) (DocInter, error)

func (*MockDatastore) UpdateMany

func (m *MockDatastore) UpdateMany(
	ctx context.Context, collection string, filter bson.D, update bson.D,
) (int64, error)

func (*MockDatastore) UpdateOne

func (m *MockDatastore) UpdateOne(
	ctx context.Context,
	collection string,
	filter bson.D,
	update bson.D,
	_ ...options.Lister[options.UpdateOneOptions],
) (int64, error)

type ObjectID

type ObjectID struct {
	bson.ObjectID `bson:"_id,omitempty"`
}

func NewObjectID

func NewObjectID() ObjectID

func (ObjectID) GetId

func (d ObjectID) GetId() any

func (ObjectID) GetObjectId

func (d ObjectID) GetObjectId() bson.ObjectID

func (ObjectID) IsZero

func (d ObjectID) IsZero() bool

func (*ObjectID) SetId

func (d *ObjectID) SetId(id any)

type Option

type Option func(*options.ClientOptions)

Option defines a function signature for configuring the MongoDB client. This follows the functional options pattern, allowing for flexible and clear configuration.

func WithMaxConnIdleTime

func WithMaxConnIdleTime(d time.Duration) Option

WithMaxConnIdleTime sets the maximum duration that a connection can remain idle in the pool.

func WithMaxPoolSize

func WithMaxPoolSize(size uint64) Option

WithMaxPoolSize specifies the maximum number of connections allowed in the connection pool.

func WithMinPoolSize

func WithMinPoolSize(size uint64) Option

WithMinPoolSize specifies the minimum number of connections to maintain in the connection pool.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the maximum duration for database operations.

func WithURI

func WithURI(uri string) Option

WithURI sets the MongoDB connection URI.

Directories

Path Synopsis
Package types provides shared, specialized data types for use with MongoDB documents.
Package types provides shared, specialized data types for use with MongoDB documents.

Jump to

Keyboard shortcuts

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