From 02592e5020e504d0ea8775be9e62f0de16a1a35b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?C=C3=A9dric=20Thomas?= Date: Fri, 3 Feb 2023 12:16:07 +0100 Subject: [PATCH] feat(count): Add count method to document package --- mongo/document/document.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/mongo/document/document.go b/mongo/document/document.go index df5791e5..e311c2fe 100644 --- a/mongo/document/document.go +++ b/mongo/document/document.go @@ -189,6 +189,28 @@ func WhereUnscoped(ctx context.Context, collectionName string, query bson.M, dat return nil } +func Count(ctx context.Context, collectionName string, query bson.M) (int, error) { + if query == nil { + query = bson.M{} + } + if _, ok := query["deleted_at"]; !ok { + query["deleted_at"] = nil + } + + return CountUnscoped(ctx, collectionName, query) +} + +func CountUnscoped(ctx context.Context, collectionName string, query bson.M) (int, error) { + log := logger.Get(ctx) + c := mongo.Session(log).Clone().DB("").C(collectionName) + + if query == nil { + query = bson.M{} + } + + return c.Find(query).Count() +} + func WhereIter(ctx context.Context, collectionName string, query bson.M, fun func(*mgo.Iter) error, sortFields ...SortField) error { if query == nil { query = bson.M{}