coremongo

package module
v0.0.19 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2026 License: MIT Imports: 21 Imported by: 0

README

GO-CORE-MONGO

Installation

go get github.com/GPA-Gruppo-Progetti-Avanzati-SRL/go-core-mongo

La libreria go-core-mongo è una libreria per il linguaggio di programmazione Go che fornisce funzionalità per interagire con un database MongoDB. Essa include strumenti e metodi per connettersi a MongoDB, gestire connessioni e configurazioni, e altre operazioni comuni necessarie per lavorare con MongoDB in applicazioni Go.

Di default permette all'applicazione di esporre le metriche del database.

Funzionalità principali

Filter Builder

Il Filter Builder è una funzionalità della libreria go-core-mongo che permette di costruire filtri per le query MongoDB a partire da una struct Go. Questa funzionalità converte una struct con tag specifici in un oggetto bson.M, che può essere utilizzato nelle query MongoDB.

La struct di input deve avere i campi taggati con:

  • field: "nome_campo_mongodb": Il nome del campo in MongoDB.
  • operator: "$operatore": L'operatore MongoDB da usare
    • operatori supportati:
      • $eq
      • $ne
      • $lt
      • $lte
      • $gt
      • $gte
      • $in
      • $nin
      • $exists
Filtro struct {
    Nome  string `field:"name" operator:"$eq"`
    Eta   int    `field:"age" operator:"$gt"`
    Tags  []string `field:"tags" operator:"$in"`
}

Il Filter Builder itera attraverso i campi della struct, legge i tag field e operator, e costruisce un filtro bson.M che può essere utilizzato nelle query MongoDB.

N.B. per il momento è supportato solo bson.M

filterStruct := Filtro{
    Nome: "Federico",
    Età:  28,
    Tags: []string{"developer", "backend", "frontend"},
}

filter, err := buildFilter(filterStruct)
if err != nil {
    log.Fatal(err)
}

// Il filtro risultante sarà:
// bson.M{
//     "name": bson.M{"$eq": "Federico"},
//     "age":  bson.M{"$gt": 28},
//     "tags": bson.M{"$in": []string{"developer", "backend", "frontend"}},
// }
Aggregation Pipeline generator

le pipeline venegono specificate nel file di configurazione che utilizza l'app che importa la go-core-mongo

Struttura delle Aggregazioni

Le aggregazioni sono definite tramite la struct Aggregation, che include:

  • Name: Il nome dell'aggregazione.
  • Collection: La collezione MongoDB su cui eseguire l'aggregazione.
  • Stages: Una lista di fasi (Stage) che compongono la pipeline di aggregazione.

Ogni Stage include:

  • Key: Una chiave per identificare i parametri della fase.
  • Operator: L'operatore MongoDB da utilizzare (es. $match, $project).
  • Args: Argomenti specifici per l'operatore.
Esecuzioni dell'aggregazione

La funzione ExecuteAggregation esegue una pipeline di aggregazione su una collezione MongoDB. Questa funzione prende il nome di un'aggregazione predefinita, i parametri per la pipeline e le opzioni di aggregazione, e restituisce un cursore MongoDB con i risultati dell'aggregazione.

Parametri:

  • ctx: Il contesto per l'esecuzione della query.
  • name: Il nome dell'aggregazione predefinita.
  • params: Una mappa di parametri da utilizzare nella pipeline di aggregazione.
  • opts: Opzioni aggiuntive per l'aggregazione.

Ritorna:

  • mongo.Cursor: Un cursore MongoDB con i risultati dell'aggregazione.
  • core.ApplicationError: Un errore applicativo in caso di fallimento.

Esempio:

ctx := context.TODO()
name := "exampleAggregation"
params := map[string]any{
    "stage1": MyFilter{Field: "value"},
}
opts := options.Aggregate()

cursor, err := service.ExecuteAggregation(ctx, name, params, opts)
if err != nil {
    log.Fatal(err)
}

for cursor.Next(ctx) {
    var result bson.M
    if err := cursor.Decode(&result); err != nil {
        log.Fatal(err)
    }
    fmt.Println(result)
}

Dettagli di implementazione

  1. La funzione cerca l'aggregazione predefinita nel mappa Aggregations utilizzando il nome fornito.
  2. Se l'aggregazione non viene trovata, restituisce un errore di tipo BusinessError.
  3. Genera la pipeline di aggregazione chiamando la funzione GenerateAggregation con l'aggregazione e i parametri forniti.
  4. Converte la pipeline in formato JSON per il logging.
  5. Esegue l'aggregazione sulla collezione specificata utilizzando il metodo Aggregate di MongoDB.
  6. Gestisce eventuali errori, inclusi i casi in cui non vengono trovati documenti (mongo.ErrNoDocuments).
  7. Restituisce il cursore con i risultati dell'aggregazione.

Questa funzione permette di eseguire aggregazioni complesse in modo dinamico, basandosi su configurazioni predefinite e parametri forniti a runtime.

Configurazione delle aggregazioni

Le aggregazioni vengono definite e configurate tramite file di configurazione (es. JSON, YAML) e caricate nell'applicazione. Questo permette di definire e modificare le pipeline di aggregazione senza dover cambiare il codice sorgente.

Esempio di configurazione YAML:

aggregations:
  - name: exampleAggregation
    collection: exampleCollection
    stages:
      - operator: $match
        key: stage1
      - operator: $project
        args:
          field: 1
      - operator: $skip
        key: skip
      - operator: $limit
        key: limit

Documentation

Index

Constants

This section is empty.

Variables

View Source
var Aggregations map[string]*Aggregation

Functions

func CountDocuments added in v0.0.7

func CountDocuments(ctx context.Context, ms *mongolks.LinkedService, filter IFilter) (int64, *core.ApplicationError)

func DeleteMany added in v0.0.15

func DeleteOne added in v0.0.15

func ExecTransaction added in v0.0.7

func ExecTransaction(ctx context.Context, ms *mongolks.LinkedService, transaction func(ctx context.Context) error) *core.ApplicationError

func ExecuteAggregation added in v0.0.4

func ExecuteAggregation[T any](ctx context.Context, ls *mongolks.LinkedService, name string, params map[string]any, opts ...options.Lister[options.AggregateOptions]) ([]*T, *core.ApplicationError)
func ExecuteAggregation(ctx context.Context,ls *mongolks.LinkedService,  name string, params map[string]any, opts ...*options.AggregateOptions) (*mongo.Cursor, *core.ApplicationError) {
	aggregation, ok := Aggregations[name]
	if !ok {
		return nil, core.BusinessErrorWithCodeAndMessage("NOT-FOUND", fmt.Sprintf("aggregation '%s' not found", name))
	}
	mp, err := GenerateAggregation(aggregation, params)

	if err != nil {
		return nil, err
	}
	if zerolog.GlobalLevel() < zerolog.DebugLevel {
		value := PipelineToJson(mp)
		log.Trace().Msg(value)
	}

	cur, errAgg := ls.GetCollection(aggregation.Collection,"").Aggregate(ctx, mp, opts...)
	if errAgg != nil {
		if errors.Is(err, mongo.ErrNoDocuments) {
			return nil, core.NotFoundError()
		}
		return nil, core.TechnicalErrorWithError(errAgg)
	}
	return cur, nil
}

func FilterToJson added in v0.0.4

func FilterToJson(filter any) string

func FindSortOption added in v0.0.16

func FindSortOption(s page.SortRequest) options.Lister[options.FindOptions]

FindSortOption converts a SortRequest into a FindOptions lister ready to be passed as a variadic argument to GetPageByFilter or any Find call.

Usage:

results, err := coremongo.GetPageByFilter(ctx, ms, filter, paging, coremongo.FindSortOption(sortReq))

func GenerateAggregation

func GenerateAggregation(a *Aggregation, params map[string]any) (mongo.Pipeline, *core.ApplicationError)

func GetIds added in v0.0.7

func GetIds(ctx context.Context, ms *mongolks.LinkedService, filter string, collectionName string, sort string, limit int) ([]string, *core.ApplicationError)

func GetObjectByFilter added in v0.0.3

func GetObjectByFilter[T ICollection](ctx context.Context, ms *mongolks.LinkedService, filter IFilter) (*T, *core.ApplicationError)

func GetObjectById added in v0.0.3

func GetObjectById[T ICollection](ctx context.Context, ms *mongolks.LinkedService, id string) (*T, *core.ApplicationError)

func GetObjectsByFilter added in v0.0.4

func GetObjectsByFilter[T ICollection](ctx context.Context, ms *mongolks.LinkedService, filter IFilter) ([]*T, *core.ApplicationError)

func GetObjectsByFilterSorted added in v0.0.6

func GetObjectsByFilterSorted[T ICollection](ctx context.Context, ms *mongolks.LinkedService, filter IFilter, sort page.SortRequest) ([]*T, *core.ApplicationError)

func GetPageByFilter added in v0.0.15

func GetPageByFilter[T ICollection](ctx context.Context, ms *mongolks.LinkedService, filter IFilter, paging *page.Paging, opts ...options.Lister[options.FindOptions]) ([]T, *core.ApplicationError)

func GetSequence added in v0.0.7

func GetSequence(ctx context.Context, ms *mongolks.LinkedService, sequenceCollection, sequenceName string) (int, *core.ApplicationError)

func InsertMany added in v0.0.7

func InsertOne added in v0.0.7

func LoadAggregations

func LoadAggregations(aggregationFolder AggregationsPath, aggregationFiles embed.FS)

func NewService

func NewService(config *mongolks.Config, lc fx.Lifecycle, mc Core) (*mongolks.LinkedService, error)

func PipelineToJson added in v0.0.4

func PipelineToJson(pipeline mongo.Pipeline) string

func PrettyPrintJson added in v0.0.4

func PrettyPrintJson(jsonStr []byte) (string, error)

func ReplaceOne added in v0.0.7

func SortToBson added in v0.0.16

func SortToBson(s page.SortRequest) bson.D

SortToBson converts a SortRequest to a bson.D. bson.D preserves insertion order, which is required for multi-field sorts.

func UpdateMany added in v0.0.7

func UpdateMany(ctx context.Context, ms *mongolks.LinkedService, filter IFilter, update bson.M, len int) *core.ApplicationError

func UpdateOne added in v0.0.7

func UpdateSingleRecord added in v0.0.7

func UpdateSingleRecord(ctx context.Context, ms *mongolks.LinkedService, collectionName string, filterR interface{}, updateR interface{}) error

Types

type Aggregation

type Aggregation struct {
	Name       string   `mapstructure:"name" json:"name" yaml:"name"`
	Collection string   `mapstructure:"collection" json:"collection" yaml:"collection"`
	Stages     []*Stage `mapstructure:"stages" json:"stages" yaml:"stages"`
}

type AggregationDirectory

type AggregationDirectory embed.FS

type AggregationsPath added in v0.0.7

type AggregationsPath string

type Core

type Core struct {
	core.In
	AggregationFiles AggregationDirectory `optional:"true"`
	AggregationPath  *AggregationsPath    `optional:"true"`
}

type GenerateStage

type GenerateStage func(function string, args map[string]interface{}, params any) (bson.D, *core.ApplicationError)

type ICollection added in v0.0.4

type ICollection interface {
	GetCollectionName(ctx context.Context) string
}

type IFilter added in v0.0.4

type IFilter interface {
	GetFilterCollectionName(ctx context.Context) string
}

type Stage

type Stage struct {
	Key      string         `mapstructure:"key" json:"key" yaml:"key"`
	Operator string         `mapstructure:"operator" json:"operator" yaml:"operator"`
	Args     map[string]any `mapstructure:"args" json:"args" yaml:"args"`
}

Directories

Path Synopsis
Package locker provides a MongoDB-backed implementation of the neutral go-core-app/lock.Locker primitive.
Package locker provides a MongoDB-backed implementation of the neutral go-core-app/lock.Locker primitive.

Jump to

Keyboard shortcuts

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