From c34b3cc9f9fb79a98eb26952e6cddba63befb82b Mon Sep 17 00:00:00 2001 From: Nikita Tokarchuk Date: Fri, 25 Jan 2019 01:28:03 +0100 Subject: [PATCH] Count func --- mongox/common/count.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 mongox/common/count.go diff --git a/mongox/common/count.go b/mongox/common/count.go new file mode 100644 index 0000000..9e789d1 --- /dev/null +++ b/mongox/common/count.go @@ -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 +}