Add sort to find

This commit is contained in:
George Suntres
2026-04-25 12:42:30 -04:00
parent 7c60f4c57b
commit 374b4b22c9
6 changed files with 27 additions and 13 deletions

20
find.go
View File

@@ -8,9 +8,10 @@ import (
)
type FindOptions struct {
Offset int64 `json:"offset"`
Limit int64 `json:"limit"`
Alias string `json:"alias"`
Offset int64 `json:"offset"`
Limit int64 `json:"limit"`
Alias string `json:"alias"`
Sort [][]any `json:"sort"`
}
// Find is used to fetch the first page of data.
@@ -31,8 +32,15 @@ func (c *MongoClient) Find(ctx context.Context, database, name string, filter bs
pageSize := max(limit, c.Limit)
sort := bson.M{"_id": 1}
sortOpts := commons.BsonDFromSlice(opts.Sort)
var sort bson.D
if len(sortOpts) == 0 {
sort = sortOpts
} else {
sort = bson.D{{Key: "_id", Value: 1}}
}
if err := c.DiscriminatorCheckAndApplyToFilter(ctx, name, filter); err != nil {
return nil, err
}
@@ -139,7 +147,9 @@ func (c *MongoClient) FindOffset(ctx context.Context, database, name string, fil
Filter: filter,
})
pipeline := BuildPaginationPipeline(offset, finalLimit, f, nil)
sort := commons.BsonDFromSlice(opts.Sort)
pipeline := BuildPaginationPipeline(offset, finalLimit, f, sort)
// 2. Query
cursor, err := collection.Aggregate(ctx, pipeline)