mongorepository

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jan 21, 2024 License: Apache-2.0 Imports: 8 Imported by: 0

README

mongo-repository

GitHub tag (latest SemVer) Go Reference License

Tests CodeQL Analysis GolangCI Lint Go Report Card

This Go package provides a generic, extensible MongoDB repository with advanced CRUD operations, flexible querying capabilities, and support for common MongoDB patterns. It is designed to simplify the interaction with MongoDB using Go's standard library and the official MongoDB Go driver.

Features

  • Generic CRUD operations for MongoDB documents.
  • Query helpers for complex filters and full-text search.
  • Support for finding documents by multiple IDs.
  • Custom index creation with various index options.
  • Batch update capabilities.

Installation

To use this MongoDB repository package, you need to have Go installed on your machine. The package can be installed using the following Go command:

go get -u github.com/dmitrymomot/mongo-repository

Usage

Import the package into your Go file:

import "github.com/dmitrymomot/mongo-repository"
Basic CRUD Operations

Here's a quick example of how you can use the repository for CRUD operations:

func main() {
    // Initialize your MongoDB client and context
    // ...

    // Create a new repository for your model
    userRepo := repository.NewMongoRepository[User](db, "users")

    // Use the repository for various operations
    // ...
}
Advanced Querying

The package includes a filter builder to create complex queries easily:

func findUsers(repo repository.Repository[User]) {
    ctx := context.TODO()
    filter := repository.And(
        repository.Gt("age", 30),
        repository.Eq("status", "active"),
    )
    users, err := repo.FindManyByFilter(ctx, 0, 10, filter)
    // Handle err and work with users
}

The package includes a full-text search builder to create text queries easily. The text search query uses the MongoDB text search feature.

How to use it - see the tests: full_text_search_test.go.

TTL Index

To create an index with a Time-To-Live (TTL) in MongoDB, which automatically deletes documents after a certain amount of time, you need to specify the TTL when creating the index. MongoDB uses a special background task that runs periodically to remove expired documents.

Creating a TTL Index in Your Collection

When you want to create an index with a TTL, specify the field and use the TTL option. This field typically stores the creation time of the document and should be of BSON date type.

// Create an index with a TTL of 24 hours
err := repo.CreateIndex(context.TODO(), "createdAt", mongorepository.TTL(24*time.Hour))
Document Structure

Ensure your documents have a field (like createdAt) that stores the time when the document was created. This field is used by MongoDB to determine if a document is expired.

type YourDocumentType struct {
    ID        primitive.ObjectID `bson:"_id,omitempty"`
    CreatedAt time.Time          `bson:"createdAt"`
    // Other fields...
}
Notes
  • MongoDB runs a background task every 60 seconds to remove expired documents, so there may be a slight delay before documents are actually deleted.
  • This approach is commonly used for data that needs to be retained only for a specific duration, such as logs, temporary data, or session information.

Contributing

Contributions to the mongo-repository package are welcome! Here are some ways you can contribute:

  • Reporting bugs
  • Additional tests cases
  • Suggesting enhancements
  • Submitting pull requests
  • Sharing the love by telling others about this project

License

This project is licensed under the Apache 2.0 - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrNotFound                 = errors.New("document not found")
	ErrDuplicate                = errors.New("document already exists")
	ErrFailedToFindByID         = errors.New("failed to find document by id")
	ErrFailedToFindByIDs        = errors.New("failed to find documents by ids")
	ErrInvalidDocumentID        = errors.New("invalid document id")
	ErrFailedToCreate           = errors.New("failed to create document")
	ErrFailedToUpdate           = errors.New("failed to update document")
	ErrFailedToUpdateMany       = errors.New("failed to update documents")
	ErrFailedToDelete           = errors.New("failed to delete document")
	ErrFailedToFindOneByFilter  = errors.New("failed to find a document by the given filter")
	ErrFailedToFindManyByFilter = errors.New("failed to find any documents by the given filter")
	ErrFailedToCreateIndex      = errors.New("failed to create collection index")
	ErrFailedToDeleteMany       = errors.New("failed to delete documents")
)

Predefined errors

Functions

func NewMongoRepository

func NewMongoRepository[T any](db *mongo.Database, collectionName string) *mongoRepository[T]

NewMongoRepository creates a new instance of the mongoRepository[T] struct. It takes a mongo.Database and a collectionName as parameters and returns a pointer to the mongoRepository[T] struct. The mongoRepository[T] struct represents a repository for working with a specific MongoDB collection. The collection field of the struct is initialized with the specified collectionName from the provided database.

Types

type FilterFunc

type FilterFunc func(bson.D) bson.D

FilterFunc is a function type that takes a BSON document and modifies it.

func And

func And(filters ...FilterFunc) FilterFunc

And combines multiple filters with a logical AND

func Eq

func Eq(field string, value interface{}) FilterFunc

Eq creates an equality filter

func Exists

func Exists(field string, exists bool) FilterFunc

Exists checks if a field exists

func Gt

func Gt(field string, value interface{}) FilterFunc

Gt creates a greater-than filter

func Gte

func Gte(field string, value interface{}) FilterFunc

Gte creates a greater-than-or-equal filter

func In

func In(field string, values interface{}) FilterFunc

In creates an "in" filter

func Lt

func Lt(field string, value interface{}) FilterFunc

Lt creates a less-than filter

func Lte

func Lte(field string, value interface{}) FilterFunc

Lte creates a less-than-or-equal filter

func Ne

func Ne(field string, value interface{}) FilterFunc

Ne creates a not-equal filter

func Or

func Or(filters ...FilterFunc) FilterFunc

Or combines multiple filters with a logical OR

func Regex

func Regex(field string, pattern string, options string) FilterFunc

Regex creates a filter for regular expression matching

func TextSearch

func TextSearch(searchTerm string) FilterFunc

TextSearch creates a full-text search filter

type IndexOption

type IndexOption func(*options.IndexOptions)

IndexOption wraps the MongoDB IndexOptions for extensibility and ease of use

func ExpireAfterSeconds

func ExpireAfterSeconds(expireAfterSeconds int32) IndexOption

ExpireAfterSeconds specifies the expireAfterSeconds option for an index

func Name

func Name(name string) IndexOption

Name specifies the name option for an index

func PartialFilterExpression

func PartialFilterExpression(partialFilterExpression interface{}) IndexOption

PartialFilterExpression specifies the partialFilterExpression option for an index

func SetCollation

func SetCollation(collation *options.Collation) IndexOption

SetCollation specifies the collation option for an index

func SetHidden

func SetHidden(hidden bool) IndexOption

SetHidden specifies the hidden option for an index

func SetWildcardProjection

func SetWildcardProjection(wildcardProjection interface{}) IndexOption

SetWildcardProjection specifies the wildcardProjection option for an index

func Sparse

func Sparse(sparse bool) IndexOption

Sparse specifies the sparse option for an index

func TTL added in v0.3.0

func TTL(duration time.Duration) IndexOption

TTL sets the Time-To-Live for an index

func TextIndex added in v0.3.0

func TextIndex(config TextIndexConfig) IndexOption

TextIndex creates a text index option with specified fields and weights

func Unique

func Unique(unique bool) IndexOption

Unique specifies the unique option for an index

type Repository

type Repository[T any] interface {
	// CreateIndex creates an index in the MongoDB collection based on the specified key and options.
	// It takes a context.Context as the first argument, the key for the index as the second argument,
	// and optional IndexOption(s) as the third argument(s).
	// The function returns an error if the index creation fails.
	CreateIndex(ctx context.Context, key interface{}, opts ...IndexOption) error

	// Create inserts a new document into the MongoDB collection.
	// It takes a context.Context and a model of type T as input parameters.
	// It returns the ID of the newly created document as a string and an error, if any.
	Create(ctx context.Context, model T) (string, error)

	// FindByID retrieves a document from the MongoDB collection by its ID.
	// It takes a context.Context and the ID of the document as parameters.
	// It returns the retrieved document of type T and an error, if any.
	FindByID(ctx context.Context, id string) (T, error)

	// FindByIDs retrieves multiple documents from the MongoDB collection by their IDs.
	// It takes a context.Context and a slice of IDs as parameters.
	// It returns a slice of documents of type T and an error, if any.
	FindByIDs(ctx context.Context, ids ...string) ([]T, error)

	// Update updates a document in the MongoDB collection with the specified ID.
	// It takes a context, ID string, and model as input parameters.
	// It returns the number of modified documents and an error, if any.
	Update(ctx context.Context, id string, model T) (int64, error)

	// UpdateMany updates multiple documents in the MongoDB collection based on the provided filters.
	// It takes a context.Context, a map of update fields, and optional filter functions as parameters.
	// The update fields specify the changes to be made to the documents.
	// The filter functions are used to build the filter for selecting the documents to be updated.
	// It returns the number of documents modified and an error if any.
	UpdateMany(ctx context.Context, update map[string]interface{}, filters ...FilterFunc) (int64, error)

	// Delete deletes a document from the MongoDB collection based on the provided ID.
	// It returns the number of deleted documents and an error, if any.
	Delete(ctx context.Context, id string) (int64, error)

	// DeleteMany deletes multiple documents from the MongoDB collection based on the provided filters.
	// It returns the number of deleted documents and an error, if any.
	DeleteMany(ctx context.Context, filters ...FilterFunc) (int64, error)

	// FindManyByFilter retrieves multiple documents from the collection based on the provided filters.
	// It allows skipping a certain number of documents and limiting the number of documents to be returned.
	// The filters are applied in the order they are passed.
	// If no documents match the filters, it returns an error with the ErrNotFound error code.
	// If an error occurs during the retrieval process, it returns an error with the ErrFailedToFindManyByFilter error code.
	// The function returns a slice of documents of type T and an error.
	FindManyByFilter(ctx context.Context, skip int64, limit int64, filters ...FilterFunc) ([]T, error)

	// FindOneByFilter finds a single document in the collection based on the provided filters.
	// It accepts one or more FilterFunc functions that modify the filter criteria.
	// The function returns the found document of type T and an error, if any.
	// If no document is found, it returns an error of type ErrNotFound.
	// If an error occurs during the find operation, it returns the error.
	FindOneByFilter(ctx context.Context, filters ...FilterFunc) (T, error)

	// Exists checks if a document exists in the collection based on the provided filters.
	// It accepts one or more FilterFunc functions that modify the filter criteria.
	// The function returns true if a document exists and false otherwise.
	// If an error occurs during the find operation, it returns the error.
	Exists(ctx context.Context, filters ...FilterFunc) (bool, error)

	// Count returns the number of documents in the collection based on the provided filters.
	// It accepts one or more FilterFunc functions that modify the filter criteria.
	// The function returns the number of documents and an error, if any.
	Count(ctx context.Context, filters ...FilterFunc) (int64, error)
}

Repository is an interface that defines the methods for interacting with a MongoDB collection.

type TextIndexConfig added in v0.3.0

type TextIndexConfig struct {
	Fields      map[string]int32 // Fields with weights
	DefaultLang string           // Default language for the index
	Name        string           // Optional custom name for the index
}

TextIndexConfig configures the text index

func NewTextIndexConfig added in v0.3.0

func NewTextIndexConfig(fields map[string]int32) TextIndexConfig

NewTextIndexConfig creates a new text index config with specified fields and weights Panics if no fields are provided

Jump to

Keyboard shortcuts

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