You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
mongox-go-driver/mongox/common/count.go

34 lines
864 B

5 years ago
package common
import (
"fmt"
4 years ago
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
4 years ago
"github.com/mainnika/mongox-go-driver/v2/mongox"
"github.com/mainnika/mongox-go-driver/v2/mongox/query"
5 years ago
)
// 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) {
5 years ago
collection := db.GetCollectionOf(target)
opts := options.Count()
composed := query.Compose(filters...)
opts.Limit = composed.Limiter()
opts.Skip = composed.Skipper()
result, err := collection.CountDocuments(db.Context(), composed.M(), opts)
5 years ago
if err == mongo.ErrNoDocuments {
return 0, err
5 years ago
}
if err != nil {
return 0, fmt.Errorf("can't decode desult: %w", err)
5 years ago
}
return result, nil
}