Add FindOptions

This commit is contained in:
George Suntres
2026-04-18 12:11:00 -04:00
parent 7599b8b856
commit 6e91f84750
4 changed files with 34 additions and 6 deletions

39
find.go
View File

@@ -7,11 +7,27 @@ import (
"git.gsuntres.com/general/commons"
)
type FindOptions struct {
Offset int64 `json:"offset"`
Limit int64 `json:"limit"`
Alias string `json:"alias"`
}
// Find is used to fetch the first page of data.
func (c *MongoClient) Find(ctx context.Context, database, name string, filter bson.M, limit int64) (bson.M, error) {
func (c *MongoClient) Find(ctx context.Context, database, name string, filter bson.M, opts *FindOptions) (bson.M, error) {
var limit int64
if opts != nil {
limit = opts.Limit
}
// 1. Prepare to query.
collection := c.GetCollection(database, name)
finalName := name
if opts != nil && commons.StringIsNotBlank(opts.Alias) {
finalName = opts.Alias
}
collection := c.GetCollection(database, finalName)
pageSize := max(limit, c.Limit)
@@ -44,8 +60,8 @@ func (c *MongoClient) Find(ctx context.Context, database, name string, filter bs
var totalValue any
if len(metadata) != 0 {
metadataRoot := metadata[0].(bson.M)
totalValue = metadataRoot["total"]
metadataRoot := metadata[0].(bson.D)
totalValue, _ = commons.BsonDGetAny(metadataRoot, "total")
}
var total int64
@@ -84,9 +100,20 @@ func (c *MongoClient) Find(ctx context.Context, database, name string, filter bs
return out, nil
}
func (c *MongoClient) FindOffset(ctx context.Context, database, name string, filter bson.M, offset, limit int64) (bson.M, error) {
func (c *MongoClient) FindOffset(ctx context.Context, database, name string, filter bson.M, opts *FindOptions) (bson.M, error) {
var offset int64
var limit int64
if opts != nil {
limit = opts.Limit
}
// 1. Prepare to query.
collection := c.GetCollection(database, name)
finalName := name
if opts != nil && commons.StringIsNotBlank(opts.Alias) {
finalName = opts.Alias
}
collection := c.GetCollection(database, finalName)
finalLimit := max(limit, c.Limit)