goext/wmo/queryAggregate.go

73 lines
2.1 KiB
Go
Raw Normal View History

2023-06-06 21:33:49 +02:00
package wmo
import (
"context"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
2023-08-21 15:08:35 +02:00
"gogs.mikescher.com/BlackForestBytes/goext/exerr"
"gogs.mikescher.com/BlackForestBytes/goext/langext"
2023-06-06 21:33:49 +02:00
)
func (c *Coll[TData]) Aggregate(ctx context.Context, pipeline mongo.Pipeline, opts ...*options.AggregateOptions) ([]TData, error) {
2024-01-09 08:51:46 +01:00
for _, ppl := range c.extraModPipeline {
pipeline = langext.ArrConcat(pipeline, ppl(ctx))
}
2023-06-06 21:33:49 +02:00
cursor, err := c.coll.Aggregate(ctx, pipeline, opts...)
if err != nil {
2023-08-21 15:08:35 +02:00
return nil, exerr.Wrap(err, "mongo-aggregation failed").Any("pipeline", pipeline).Any("options", opts).Str("collection", c.Name()).Build()
2023-06-06 21:33:49 +02:00
}
2023-06-10 16:22:14 +02:00
res, err := c.decodeAll(ctx, cursor)
2023-06-06 21:33:49 +02:00
if err != nil {
2023-08-21 15:08:35 +02:00
return nil, exerr.Wrap(err, "failed to decode values").Build()
2023-06-06 21:33:49 +02:00
}
return res, nil
}
2023-06-10 16:28:50 +02:00
func (c *Coll[TData]) AggregateOneOpt(ctx context.Context, pipeline mongo.Pipeline, opts ...*options.AggregateOptions) (*TData, error) {
2024-01-09 08:51:46 +01:00
for _, ppl := range c.extraModPipeline {
pipeline = langext.ArrConcat(pipeline, ppl(ctx))
}
2023-06-10 16:28:50 +02:00
cursor, err := c.coll.Aggregate(ctx, pipeline, opts...)
if err != nil {
2023-08-21 15:08:35 +02:00
return nil, exerr.Wrap(err, "mongo-aggregation failed").Any("pipeline", pipeline).Any("options", opts).Str("collection", c.Name()).Build()
2023-06-10 16:28:50 +02:00
}
if cursor.Next(ctx) {
v, err := c.decodeSingle(ctx, cursor)
if err != nil {
2023-08-21 15:08:35 +02:00
return nil, exerr.Wrap(err, "failed to decode single value").Build()
2023-06-10 16:28:50 +02:00
}
return &v, nil
}
return nil, nil
}
2023-07-17 12:42:49 +02:00
func (c *Coll[TData]) AggregateOne(ctx context.Context, pipeline mongo.Pipeline, opts ...*options.AggregateOptions) (TData, error) {
2024-01-09 08:51:46 +01:00
for _, ppl := range c.extraModPipeline {
pipeline = langext.ArrConcat(pipeline, ppl(ctx))
}
2023-07-17 12:42:49 +02:00
cursor, err := c.coll.Aggregate(ctx, pipeline, opts...)
if err != nil {
2023-08-21 15:08:35 +02:00
return *new(TData), exerr.Wrap(err, "mongo-aggregation failed").Any("pipeline", pipeline).Any("options", opts).Str("collection", c.Name()).Build()
2023-07-17 12:42:49 +02:00
}
if cursor.Next(ctx) {
v, err := c.decodeSingle(ctx, cursor)
if err != nil {
2023-08-21 15:08:35 +02:00
return *new(TData), exerr.Wrap(err, "failed to decode single value").Build()
2023-07-17 12:42:49 +02:00
}
return v, nil
}
2023-08-21 15:08:35 +02:00
return *new(TData), exerr.Wrap(mongo.ErrNoDocuments, "no document in result").Build()
2023-07-17 12:42:49 +02:00
}