mirror of
https://github.com/mainnika/mongox-go-driver.git
synced 2026-05-22 15:53:36 +00:00
Count func
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"github.com/mainnika/mongox-go-driver/mongox"
|
||||
"github.com/mainnika/mongox-go-driver/mongox/errors"
|
||||
"github.com/mainnika/mongox-go-driver/mongox/query"
|
||||
"github.com/mongodb/mongo-go-driver/mongo"
|
||||
"github.com/mongodb/mongo-go-driver/mongo/options"
|
||||
)
|
||||
|
||||
// Count function counts documents in the database by query
|
||||
// target is used only to get collection by tag so it'd be better to use nil ptr here
|
||||
func Count(db *mongox.Database, target interface{}, filters ...interface{}) (int64, error) {
|
||||
|
||||
collection := db.GetCollectionOf(target)
|
||||
opts := options.Count()
|
||||
composed := query.Compose(filters...)
|
||||
|
||||
opts.Limit = composed.Limiter()
|
||||
opts.Skip = composed.Skipper()
|
||||
|
||||
result, err := collection.Count(db.Context(), composed.M(), opts)
|
||||
if err == mongo.ErrNoDocuments {
|
||||
return 0, errors.NotFoundErrorf("%s", err)
|
||||
}
|
||||
if err != nil {
|
||||
return 0, errors.InternalErrorf("can't decode desult: %s", err)
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
Reference in New Issue
Block a user