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
- Variables
- func Close(ctx context.Context) error
- func CountDocument(ctx context.Context, collectionName string, filter any) (int64, error)
- func DeleteById[T DocInter](ctx context.Context, doc T) (int64, error)
- func DeleteMany[T DocInter](ctx context.Context, doc T, filter bson.D) (int64, error)
- func DeleteOne[T DocInter](ctx context.Context, doc T, filter bson.D) (int64, error)
- func Distinct[T any](ctx context.Context, collectionName string, field string, filter any, ...) ([]T, error)
- func Find[T DocInter](ctx context.Context, doc T, filter any, limit uint16, ...) ([]T, error)
- func FindById[T DocInter](ctx context.Context, doc T) error
- func FindOne[T DocInter](ctx context.Context, doc T, filter any, ...) error
- func GetDatabase() *mongo.Database
- func Import(ctx context.Context, collectionName string, reader io.Reader) error
- func InitConnection(ctx context.Context, dbName string, tracer trace.Tracer, opts ...Option) error
- func IsCollectionExist(ctx context.Context, collectionName string) (bool, error)
- func IsConnected() bool
- func IsHealth(ctx context.Context) error
- func NewEmptyModel[T DocWithInitIndex]() T
- func NewErrOnFind(err error) ...
- func NewErrOnFindOne(err error) ...
- func NewModelWithId[T DocWithId](opts ...DocInterOpt) T
- func NewOnBulkOperationMock(result *mongo.BulkWriteResult, err error) func(cname string) BulkOperator
- func NewOnFindMock(fakeData ...any) ...
- func NewOnFindOneMock(fakeData any) ...
- func NewOnPipeFindMock(fakeData ...any) func(_ context.Context, _ string, _ mongo.Pipeline) (*mongo.Cursor, error)
- func NewOnSaveMock() func(ctx context.Context, doc DocInter) (DocInter, error)
- func PipeFind[T MgoAggregate](ctx context.Context, aggr T, filter bson.M, limit uint16) ([]T, error)
- func PipeFindByPipeline[T any](ctx context.Context, collectionName string, pipeline mongo.Pipeline, ...) ([]T, error)
- func PipeFindOne[T MgoAggregate](ctx context.Context, aggr T, filter bson.M) error
- func RegisterIndex(index Index)
- func ReplaceOne[T DocInter](ctx context.Context, doc T, filter any, ...) (int64, error)
- func Save[T DocInter](ctx context.Context, doc T) (T, error)
- func SetDatastore(mock Datastore) (restore func())
- func SyncIndexes(ctx context.Context) error
- func ToStatus(err error) *status.Status
- func UpdateById[T DocInter](ctx context.Context, doc T, update bson.D) (int64, error)
- func UpdateMany[T DocInter](ctx context.Context, doc T, filter bson.D, update bson.D) (int64, error)
- func UpdateOne[T DocInter](ctx context.Context, doc T, filter bson.D, update bson.D) (int64, error)
- type BulkOperator
- type Datastore
- type DocInter
- type DocInterOpt
- type DocWithId
- type DocWithInitIndex
- type Index
- type MgoAggregate
- type MigrationInfo
- type MockBulkOperator
- func (m *MockBulkOperator) DeleteById(id any) BulkOperator
- func (m *MockBulkOperator) DeleteOne(filter any) BulkOperator
- func (m *MockBulkOperator) Execute(ctx context.Context) (*mongo.BulkWriteResult, error)
- func (m *MockBulkOperator) InsertOne(doc DocInter) BulkOperator
- func (m *MockBulkOperator) UpdateById(id any, update any) BulkOperator
- func (m *MockBulkOperator) UpdateOne(filter any, update any) BulkOperator
- func (m *MockBulkOperator) UpsertOne(filter any, update any) BulkOperator
- type MockDatastore
- func (m *MockDatastore) CountDocument(ctx context.Context, collectionName string, filter any) (int64, error)
- func (m *MockDatastore) DeleteMany(ctx context.Context, collection string, filter bson.D) (int64, error)
- func (m *MockDatastore) DeleteOne(ctx context.Context, collection string, filter bson.D) (int64, error)
- func (m *MockDatastore) Distinct(ctx context.Context, collectionName string, field string, filter any, ...) ([]bson.RawValue, error)
- func (m *MockDatastore) Find(ctx context.Context, collection string, filter any, ...) (*mongo.Cursor, error)
- func (m *MockDatastore) FindOne(ctx context.Context, collection string, filter any, ...) *mongo.SingleResult
- func (m *MockDatastore) Import(ctx context.Context, collectionName string, reader io.Reader) error
- func (m *MockDatastore) NewBulkOperation(cname string) BulkOperator
- func (m *MockDatastore) PipeFind(ctx context.Context, collection string, pipeline mongo.Pipeline) (*mongo.Cursor, error)
- func (m *MockDatastore) PipeFindOne(ctx context.Context, collection string, pipeline mongo.Pipeline) *mongo.SingleResult
- func (m *MockDatastore) ReplaceOne(ctx context.Context, collection string, filter any, replacement any, ...) (*mongo.UpdateResult, error)
- func (m *MockDatastore) Save(ctx context.Context, doc DocInter) (DocInter, error)
- func (m *MockDatastore) UpdateMany(ctx context.Context, collection string, filter bson.D, update bson.D) (int64, error)
- func (m *MockDatastore) UpdateOne(ctx context.Context, collection string, filter bson.D, update bson.D, ...) (int64, error)
- type ObjectID
- type Option
Constants ¶
const ( MigrateStatusPending migrateStatus = "pending" MigrateStatusRunning migrateStatus = "running" MigrateStatusSuccess migrateStatus = "success" MigrateStatusFailed migrateStatus = "failed" )
Variables ¶
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 ¶
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 DeleteById ¶
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 ¶
DeleteMany deletes all documents matching the filter. doc: An instance of the document type, used to determine the collection.
func DeleteOne ¶
DeleteOne deletes a single document matching the filter. doc: An instance of the document type, used to determine the collection.
func GetDatabase ¶
func InitConnection ¶
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 IsCollectionExist ¶
func IsConnected ¶
func IsConnected() bool
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 ¶
NewOnSaveMock returns an OnSave function that simulates a successful save. It assigns a new ObjectID to the document and returns it.
func PipeFindByPipeline ¶
func PipeFindOne ¶
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 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 ¶
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 UpdateById ¶
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 UpdateOne ¶
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 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 MigrationInfo ¶
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 (m *MockBulkOperator) Execute(ctx context.Context) (*mongo.BulkWriteResult, error)
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 (*MockDatastore) DeleteMany ¶
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) FindOne ¶
func (m *MockDatastore) FindOne( ctx context.Context, collection string, filter any, opts ...options.Lister[options.FindOneOptions], ) *mongo.SingleResult
func (*MockDatastore) NewBulkOperation ¶
func (m *MockDatastore) NewBulkOperation(cname string) BulkOperator
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) UpdateMany ¶
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 ¶
WithMaxConnIdleTime sets the maximum duration that a connection can remain idle in the pool.
func WithMaxPoolSize ¶
WithMaxPoolSize specifies the maximum number of connections allowed in the connection pool.
func WithMinPoolSize ¶
WithMinPoolSize specifies the minimum number of connections to maintain in the connection pool.
func WithTimeout ¶
WithTimeout sets the maximum duration for database operations.