{"id":15731842,"url":"https://github.com/GabrielHCataldo/go-mongo-template","last_synced_at":"2025-10-14T22:30:33.670Z","repository":{"id":213768630,"uuid":"732729145","full_name":"GabrielHCataldo/go-mongo-template","owner":"GabrielHCataldo","description":"🍃 Powerful Template for MongoDB, with all functions and interactions optimized and simple to use.","archived":false,"fork":false,"pushed_at":"2024-03-04T10:33:01.000Z","size":263,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-01T04:01:50.459Z","etag":null,"topics":["database","go-mongo","go-mongodb","go-sql","mongo","mongodb","mongodb-database","nosql","nosql-database"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/GabrielHCataldo/go-mongo-template/mongo","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GabrielHCataldo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-12-17T16:38:21.000Z","updated_at":"2024-01-17T04:31:28.000Z","dependencies_parsed_at":"2024-01-07T17:24:01.746Z","dependency_job_id":"1eb46d0e-9c4a-4dc3-ae79-4374e2fad0ad","html_url":"https://github.com/GabrielHCataldo/go-mongo-template","commit_stats":{"total_commits":53,"total_committers":2,"mean_commits":26.5,"dds":"0.018867924528301883","last_synced_commit":"d65785d690953a1f3bb45dd71aa7e645af2d6899"},"previous_names":["gabrielhcataldo/go-mongo","gabrielhcataldo/go-mongo-template"],"tags_count":23,"template":false,"template_full_name":null,"purl":"pkg:github/GabrielHCataldo/go-mongo-template","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielHCataldo%2Fgo-mongo-template","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielHCataldo%2Fgo-mongo-template/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielHCataldo%2Fgo-mongo-template/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielHCataldo%2Fgo-mongo-template/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GabrielHCataldo","download_url":"https://codeload.github.com/GabrielHCataldo/go-mongo-template/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GabrielHCataldo%2Fgo-mongo-template/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279021785,"owners_count":26087056,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-14T02:00:06.444Z","response_time":60,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["database","go-mongo","go-mongodb","go-sql","mongo","mongodb","mongodb-database","nosql","nosql-database"],"created_at":"2024-10-04T00:06:16.547Z","updated_at":"2025-10-14T22:30:33.355Z","avatar_url":"https://github.com/GabrielHCataldo.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"MongoDB Template\n=================\n\u003c!--suppress ALL --\u003e\n\u003cimg align=\"right\" src=\"gopher-mongo.png\" alt=\"\"\u003e\n\n[![Project status](https://img.shields.io/badge/version-v1.2.2-vividgreen.svg)](https://github.com/GabrielHCataldo/go-mongo-template/releases/tag/v1.2.2)\n[![Go Report Card](https://goreportcard.com/badge/github.com/GabrielHCataldo/go-mongo-template)](https://goreportcard.com/report/github.com/GabrielHCataldo/go-mongo-template)\n[![Coverage Status](https://coveralls.io/repos/GabrielHCataldo/go-mongo-template/badge.svg?branch=main\u0026service=github)](https://coveralls.io/github/GabrielHCataldo/go-mongo?branch=main)\n[![Open Source Helpers](https://www.codetriage.com/gabrielhcataldo/go-mongo-template/badges/users.svg)](https://www.codetriage.com/gabrielhcataldo/go-mongo)\n[![MongoDoc](https://badgen.net/badge/mongo/doc/green)](https://mongodb.com/docs/drivers/go/current/)\n[![MongoDriver](https://badgen.net/badge/mongo/driver/green)](https://github.com/mongodb/mongo-go-driver)\n[![GoDoc](https://godoc.org/github/GabrielHCataldo/go-mongo?status.svg)](https://pkg.go.dev/github.com/GabrielHCataldo/go-mongo-template/mongo)\n![License](https://img.shields.io/dub/l/vibe-d.svg)\n\n[//]: # ([![build workflow]\u0026#40;https://github.com/GabrielHCataldo/go-mongo-template/actions/workflows/go.yml/badge.svg\u0026#41;]\u0026#40;https://github.com/GabrielHCataldo/go-mongo-template/actions\u0026#41;)\n[//]: # ([![Source graph]\u0026#40;https://sourcegraph.com/github.com/go-mongo-template/mongo/-/badge.svg\u0026#41;]\u0026#40;https://sourcegraph.com/github.com/go-mongo-template/mongo?badge\u0026#41;)\n[//]: # ([![TODOs]\u0026#40;https://badgen.net/https/api.tickgit.com/badgen/github.com/GabrielHCataldo/go-mongo-template/mongo\u0026#41;]\u0026#40;https://www.tickgit.com/browse?repo=github.com/GabrielHCataldo/go-mongo-template\u0026#41;)\n\nThe go-mongo-template project came to facilitate the use of the mongo driver in your go project,\nwith self-management of sessions, simplicity in configuring the database and collection directly in the structure and\nmuch more. See below some implemented features:\n\n- Simplicity in function calls without having to use getDatabase and getCollection.\n- Database and collection configuration directly in the structure.\n- Autofill id generated when inserting the document.\n- Automatic rollback if an error occurs during transactions in a session. (Optional)\n- Ease of opening and closing sessions, and also aborting or committing transactions.\n- Pre-developed functions such as **FindOneById**, **FindAll**, **FindPageable**, **Exists**, among others.\n- Easy and intuitive pagination scheme.\n- Watching events has never been easier, with automatic calls to handler functions, with a context ready to work.\n\nInstallation\n------------\n\nUse go get.\n\n\tgo get github.com/GabrielHCataldo/go-mongo-template\n\nThen import the go-mongo package into your own code.\n\n```go\nimport \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n```\n\nUsability and documentation\n------------\nBelow we will show some basic examples:\n\n- [Insert](#insert)\n- [Update](#update)\n- [Replace](#replace)\n- [Delete](#delete)\n- [Find](#find)\n- [Exists](#exists)\n- [Count](#count)\n- [Watch](#watch)\n\n**IMPORTANT**: Always check the documentation in the structures and functions fields.\nFor more details on the examples, visit [All examples link](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example).\n\n## Insert\n\nTo insert a document, it's very simple, first let's configure a structure\nTo be able to work with go-mongo, see:\n\n```go\npackage main\n\nimport \"go.mongodb.org/mongo-driver/bson/primitive\"\n\ntype test struct {\n    Id        primitive.ObjectID `json:\"id,omitempty\" bson:\"_id,omitempty\" database:\"test\" collection:\"test\"`\n    Random    int                `json:\"random,omitempty\" bson:\"random,omitempty\"`\n    Name      string             `json:\"name,omitempty\" bson:\"name,omitempty\"`\n    BirthDate primitive.DateTime `json:\"birthDate,omitempty\" bson:\"birthDate,omitempty\"`\n    Emails    []string           `json:\"emails,omitempty\" bson:\"emails,omitempty\"`\n    Balance   float64            `json:\"balance,omitempty\" bson:\"balance,omitempty\"`\n    CreatedAt primitive.DateTime `json:\"createdAt,omitempty\" bson:\"createdAt,omitempty\"`\n}\n```\n\nAs shown in the structure above, it is important to continue, the **database** tags with the name\nfrom your database and **collection** with the name of your collection. With this example structure\nWe were able to continue with the following interactions:\n\nInsert a document into the collection see:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    testDocument := test{\n        Random:    rand.Int(),\n        Name:      \"Foo Bar\",\n        BirthDate: primitive.NewDateTimeFromTime(time.Date(1999, 1, 21, 0, 0, 0, 0, time.Local)),\n        Emails:    []string{\"foobar@gmail.com\", \"foobar3@hotmail.com\"},\n        Balance:   190.12,\n        CreatedAt: primitive.NewDateTimeFromTime(time.Now()),\n    }\n    //new document need a pointer\n    err = mongoTemplate.InsertOne(ctx, \u0026testDocument)\n    if helper.IsNotNil(err) {\n        logger.Error(\"error insert document:\", err)\n    } else {\n        logger.Info(\"document inserted successfully:\", testDocument)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 13:02:07] main.go:35: document inserted successfully: {\"id\":\"65b8a8b753748d924631520c\",\"random\":6628457526937947134,\"name\":\"Foo Bar\",\"birthDate\":\"1999-01-21T02:00:00Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"balance\":190.12,\"createdAt\":\"2023-12-22T16:02:07.322Z\"}\n\nWe are able to insert multiple documents, remembering that if no ID is provided, and if you have\nconfigured a field with annotation **bson** _id and the type is **primitive.ObjectId** we will fill in the\ndocuments with identifiers generated by MongoDB, see:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo/option\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    testDocuments := []*test{\n        {\n            Random:    rand.Int(),\n            Name:      \"Foo Bar\",\n            BirthDate: primitive.NewDateTimeFromTime(time.Date(1999, 1, 21, 0, 0, 0, 0, time.Local)),\n            Emails:    []string{\"foobar@gmail.com\", \"foobar3@hotmail.com\"},\n            Balance:   190.12,\n            CreatedAt: primitive.NewDateTimeFromTime(time.Now()),\n        },\n        {\n            Random:    rand.Int(),\n            Name:      \"Foo Bar 2\",\n            BirthDate: primitive.NewDateTimeFromTime(time.Date(1999, 1, 21, 0, 0, 0, 0, time.Local)),\n            Emails:    []string{\"foobar2@gmail.com\", \"foobar4@hotmail.com\"},\n            Balance:   290.12,\n            CreatedAt: primitive.NewDateTimeFromTime(time.Now()),\n        },\n    }\n    //new document need a slice of the pointer\n    err = mongoTemplate.InsertMany(ctx, testDocuments)\n    if helper.IsNotNil(err) {\n        logger.Error(\"error insert document:\", err)\n    } else {\n        logger.Info(\"document inserted successfully:\", testDocuments)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 16:11:33] main.go:46: document inserted successfully: [{\"balance\":190.12,\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2023-12-22T19:11:33.206Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"id\":\"65b8a8b753748d924631520b\",\"name\":\"Foo Bar\",\"random\":8094092400336225232},{\"balance\":290.12,\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2023-12-22T19:11:33.206Z\",\"emails\":[\"foobar2@gmail.com\",\"foobar4@hotmail.com\"],\"id\":\"65b8a8b753748d924631520f\",\"name\":\"Foo Bar 2\",\"random\":4318945546650338065}]\n\nFor more insert examples visit [link](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/insert/main).\n\n## Update\n\nWe will perform two simple update operations, see below using **UpdateOne**:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    filter := bson.M{\"_id\": bson.M{\"$exists\": true}}\n    update := bson.M{\"$set\": bson.M{\"name\": \"Foo Bar Updated\"}}\n    updateResult, err := mongoTemplate.UpdateOne(ctx, filter, update, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error update document:\", err)\n    } else {\n        logger.Info(\"document updated successfully:\", updateResult)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 16:29:23] main.go:29: document updated successfully: {\"MatchedCount\":1,\"ModifiedCount\":1,\"UpsertedCount\":0,\"UpsertedID\":null}\n\nIf you wanted to filter only with the document id, use the **UpdateOneById** function:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    objectId, _ := primitive.ObjectIDFromHex(\"6585f3a8bf2af8ad9bcab912\")\n    update := bson.M{\"$set\": bson.M{\"name\": \"Foo Bar Updated\"}}\n    updateResult, err := mongoTemplate.UpdateOneById(ctx, objectId, update, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error update document:\", err)\n    } else {\n        logger.Info(\"document updated successfully:\", updateResult)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 17:47:00] main.go:29: document updated successfully: {\"MatchedCount\":1,\"ModifiedCount\":1,\"UpsertedCount\":0,\"UpsertedID\":null}\n\nWe can also use the **UpdateMany** function to update multiple documents, see\nin the example below:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    filter := bson.M{\"_id\": bson.M{\"$exists\": true}}\n    update := bson.M{\"$set\": bson.M{\"name\": \"Foo Bar Updated\"}}\n    updateResult, err := mongoTemplate.UpdateOne(ctx, filter, update, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error update documents:\", err)\n    } else {\n        logger.Info(\"document updated successfully:\", updateResult)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 16:31:41] main.go:29: document updated successfully: {\"MatchedCount\":13,\"ModifiedCount\":13,\"UpsertedCount\":0,\"UpsertedID\":null}\n\nFor more update examples visit [link](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/update/main).\n\n## Replace\n\nTo replace a document, see the example below:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"math/rand\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    filter := bson.M{\"_id\": bson.M{\"$exists\": true}}\n    replacement := test{\n        Random:    rand.Int(),\n        Name:      \"Foo Bar\",\n        BirthDate: primitive.NewDateTimeFromTime(time.Date(1999, 1, 21, 0, 0, 0, 0, time.Local)),\n        Emails:    []string{\"foobar@gmail.com\", \"foobar3@hotmail.com\"},\n        Balance:   190.12,\n        CreatedAt: primitive.NewDateTimeFromTime(time.Now()),\n    }\n    updateResult, err := mongoTemplate.ReplaceOne(ctx, filter, replacement, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error replace document:\", err)\n    } else {\n        logger.Info(\"document replaced successfully:\", updateResult)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 17:21:49] main.go:37: document replaced successfully: {\"MatchedCount\":1,\"ModifiedCount\":1,\"UpsertedCount\":0,\"UpsertedID\":null}\n\nFor more replace examples visit [link](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/replace/main).\n\n## Delete\n\nLet's start by removing just one document using the simple filter, see below:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    filter := bson.M{\"_id\": bson.M{\"$exists\": true}}\n    deleteResult, err := mongoTemplate.DeleteOne(ctx, filter, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error delete document:\", err)\n    } else {\n        logger.Info(\"document deleted successfully:\", deleteResult)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 17:38:06] main.go:53: document deleted successfully: {\"DeletedCount\":1}\n\nWe can remove a document by passing it as a parameter as in the example below:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    objectId, _ := primitive.ObjectIDFromHex(\"6585f3a8bf2af8ad9bcab912\")\n    deleteResult, err := mongoTemplate.DeleteOneById(ctx, objectId, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error delete document:\", err)\n    } else {\n        logger.Info(\"document deleted successfully:\", deleteResult)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 17:41:50] main.go:28: document deleted successfully: {\"DeletedCount\":1}\n\nAnd finally, we can remove several documents using the indicated filter:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    filter := bson.M{\"_id\": bson.M{\"$exists\": true}}\n    deleteResult, err := mongoTemplate.DeleteMany(ctx, filter, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error delete documents:\", err)\n    } else {\n        logger.Info(\"documents deleted successfully:\", deleteResult)\n    }\n}\n```\n\nOutput\n\n    [INFO 2023/12/22 17:50:01] main.go:28: documents deleted successfully: {\"DeletedCount\":8}\n\nFor more delete examples visit [link](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/delete/main).\n\n## Find\n\nObtaining all the documents is very simple, see the example below:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    //dest need a pointer\n    var dest []test\n    err = mongoTemplate.FindAll(ctx, \u0026dest)\n    if helper.IsNotNil(err) {\n        logger.Error(\"error find all documents:\", err)\n    } else {\n        logger.Info(\"find all documents successfully:\", dest)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 17:02:22] main.go:28: find all documents successfully: [{\"balance\":190.12,\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2023-12-22T18:53:26.695Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"id\":\"65b8a8b753748d924631520g\",\"name\":\"Foo Bar Updated\",\"random\":2576121145493409319},{\"balance\":190.12,\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2023-12-22T19:11:33.206Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"id\":\"65b8a8b753748d924631520j\",\"name\":\"Foo Bar\",\"random\":8094092400336225232},{\"balance\":290.12,\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2023-12-22T19:11:33.206Z\",\"emails\":[\"foobar2@gmail.com\",\"foobar4@hotmail.com\"],\"id\":\"65b8a8b753748d924631520k\",\"name\":\"Foo Bar 2\",\"random\":4318945546650338065}]\n\nBe able to page in a simple and intuitive way, see:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    filter := bson.M{\"_id\": bson.M{\"$exists\": true}}\n    pageOutput, err := mongoTemplate.FindPageable(ctx, filter, mongo.PageInput{\n        Page:     0,\n        PageSize: 10,\n        Ref:      []test{}, //need a slice of the structure\n        Sort:     bson.M{\"createdAt\": mongo.SortDesc},\n    })\n    if helper.IsNotNil(err) {\n        logger.Error(\"error find pageable documents:\", err)\n    } else {\n        var dest []test\n        _ = pageOutput.Content.Decode(\u0026dest)\n        logger.Info(\"find pageable documents successfully:\", pageOutput)\n        logger.Info(\"find pageable get first value:\", dest[0])\n    }\n}\n```\n\nOutput:\n\n    [INFO 2024/01/30 04:57:45] main.go:33: find pageable documents successfully: {\"page\":null,\"pageSize\":\"10\",\"pageTotal\":\"1\",\"totalElements\":\"2\",\"content\":[{\"balance\":\"190.12\",\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2024-01-30T07:57:35.865Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"id\":\"65b8abef44f575c583b91a81\",\"name\":\"Foo Bar\",\"random\":\"5208816839613347000\"},{\"balance\":\"290.12\",\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2024-01-30T07:57:35.865Z\",\"emails\":[\"foobar2@gmail.com\",\"foobar4@hotmail.com\"],\"id\":\"65b8abef44f575c583b91a82\",\"name\":\"Foo Bar 2\",\"random\":\"1873557180388720600\"}],\"lastQueryAt\":\"2024-01-30T07:57:45.444808Z\"}\n    [INFO 2024/01/30 04:57:45] main.go:34: find pageable get first value: {\"id\":\"65b8abef44f575c583b91a81\",\"random\":\"5208816839613347000\",\"name\":\"Foo Bar\",\"birthDate\":\"1999-01-21T02:00:00Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"balance\":\"190.12\",\"createdAt\":\"2024-01-30T07:57:35.865Z\"}\n\nAlso obtain a single document by id, see below:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    objectId, _ := primitive.ObjectIDFromHex(\"6585db26633e225cbeadf553\")\n    //dest need a pointer\n    var dest test\n    err = mongoTemplate.FindOneById(ctx, objectId, \u0026dest)\n    if helper.IsNotNil(err) {\n        logger.Error(\"error find all documents:\", err)\n    } else {\n        logger.Info(\"find by id document successfully:\", dest)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 17:14:47] main.go:29: find by id document successfully: {\"id\":\"65b8a8b753748d924631521z\",\"random\":2576121145493409319,\"name\":\"Foo Bar Updated\",\"birthDate\":\"1999-01-21T02:00:00Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"balance\":190.12,\"createdAt\":\"2023-12-22T18:53:26.695Z\"}\n\nFor more find examples visit [link](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/find/main).\n\n## Exists\n\nCheck if the document exists by id:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    objectId, _ := primitive.ObjectIDFromHex(\"6585f5b8fd8fa97d562419f7\")\n    exists, err := mongoTemplate.ExistsById(ctx, objectId, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error check exists document:\", err)\n    } else {\n        logger.Info(\"document exists:\", exists)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 17:56:24] main.go:27: document exists: true\n\nCheck if the document exists using the filter:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    filter := bson.M{\"_id\": bson.M{\"$exists\": true}}\n    exists, err := mongoTemplate.Exists(ctx, filter, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error check exists document:\", err)\n    } else {\n        logger.Info(\"document exists:\", exists)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 17:57:46] main.go:28: document exists: true\n\nFor more examples of exists visit [link](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/exists/main).\n\n## Count\n\nWe start with the total counter, see:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    countResult, err := mongoTemplate.EstimatedDocumentCount(ctx, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error estimated document count:\", err)\n    } else {\n        logger.Info(\"estimated document count successfully:\", countResult)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 18:26:44] main.go:27: estimated document count successfully: 16\n\nYou can also count the documents using the filter:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    filter := bson.M{\"_id\": bson.M{\"$exists\": true}}\n    countResult, err := mongoTemplate.CountDocuments(ctx, filter, test{})\n    if helper.IsNotNil(err) {\n        logger.Error(\"error count documents:\", err)\n    } else {\n        logger.Info(\"count documents successfully:\", countResult)\n    }\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 18:23:47] main.go:28: count documents successfully: 10\n\n## Watch\n\nTo watch the operations we highlight the **WatchWithHandler**, where it will persist the searches and\nwill convert the received data, transforming it into a **EventContext** where it will have all the necessary data, then\nAfter the conversion, we call the function informed in the function parameter, see a basic example:\n\n```go\npackage main\n\nimport (\n    \"context\"\n    \"github.com/GabrielHCataldo/go-helper/helper\"\n    \"github.com/GabrielHCataldo/go-logger/logger\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo\"\n    \"github.com/GabrielHCataldo/go-mongo-template/mongo/option\"\n    \"go.mongodb.org/mongo-driver/bson\"\n    \"go.mongodb.org/mongo-driver/bson/primitive\"\n    \"go.mongodb.org/mongo-driver/mongo/options\"\n    \"os\"\n    \"time\"\n)\n\nfunc main() {\n    ctx, cancel := context.WithTimeout(context.TODO(), 5*time.Second)\n    defer cancel()\n    mongoTemplate, err := mongo.NewTemplate(ctx, options.Client().ApplyURI(os.Getenv(\"MONGODB_URL\")))\n    if helper.IsNotNil(err) {\n        logger.Error(\"error to init mongo template:\", err)\n        return\n    }\n    defer mongoTemplate.SimpleDisconnect(ctx)\n    pipeline := mongo.Pipeline{bson.D{{\"$match\", bson.D{\n        {\"operationType\", bson.M{\"$in\": []string{\"insert\", \"update\", \"delete\", \"replace\"}}},\n    }}}}\n\topt := option.NewWatchWithHandler().SetDatabaseName(\"test\")\n    err = mongoTemplate.WatchWithHandler(context.TODO(), pipeline, handler, opt)\n    if helper.IsNotNil(err) {\n        logger.Error(\"error watch handler:\", err)\n    } else {\n        logger.Info(\"watch handler complete successfully\")\n    }\n}\n\nfunc handler(ctx *mongo.EventContext) {\n\tlogger.Info(\"handler called:\", ctx)\n}\n```\n\nOutput:\n\n    [INFO 2023/12/22 18:39:42] main.go:36: handler called: {\"Event\":{\"ClusterTime\":{\"I\":5,\"T\":1703281182},\"DocumentKey\":{\"ID\":[101,134,2,30,136,59,150,210,55,170,55,135]},\"FullDocument\":{\"_id\":[101,134,2,30,136,59,150,210,55,170,55,135],\"balance\":190.12,\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2023-12-22T21:39:42.288Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"name\":\"Foo Bar\",\"random\":2217047455415420974},\"NS\":{\"Coll\":\"test\",\"DB\":\"test\"},\"OperationType\":\"insert\",\"UpdateDescription\":{\"RemovedFields\":null,\"TruncatedArrays\":null,\"UpdatedFields\":null}}}\n    [INFO 2023/12/22 18:42:51] main.go:36: handler called: {\"Event\":{\"ClusterTime\":{\"I\":9,\"T\":1703281182},\"DocumentKey\":{\"ID\":[101,134,2,30,136,59,150,210,55,170,55,137]},\"FullDocument\":{\"_id\":[101,134,2,30,136,59,150,210,55,170,55,137],\"balance\":190.12,\"birthDate\":\"1999-01-21T02:00:00Z\",\"createdAt\":\"2023-12-22T21:39:42.627Z\",\"emails\":[\"foobar@gmail.com\",\"foobar3@hotmail.com\"],\"name\":\"Foo Bar\",\"random\":2251712412936242638},\"NS\":{\"Coll\":\"test\",\"DB\":\"test\"},\"OperationType\":\"insert\",\"UpdateDescription\":{\"RemovedFields\":null,\"TruncatedArrays\":null,\"UpdatedFields\":null}}}\n    Process finished with the exit code 130 (interrupted by signal 2:SIGINT)\n\nFor more watch examples visit [link](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/watch/main).\n\n## Other Examples\n\nBelow are some examples that were not shown or cited:\n\n- [Aggregate](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/aggregate/main)\n- [Distinct](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/distinct/main)\n- [Watch](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/watch/main)\n- [Drop](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/drop/main)\n- [Indexes](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/indexes/main)\n- [EventHandler Session and Transaction](https://github/GabrielHCataldo/go-mongo-template/blob/main/_example/session/main)\n\nHow to contribute\n------\nMake a pull request, or if you find a bug, open it\nan Issues.\n\nLicense\n-------\nDistributed under MIT license, see the license file within the code for more details.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGabrielHCataldo%2Fgo-mongo-template","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FGabrielHCataldo%2Fgo-mongo-template","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGabrielHCataldo%2Fgo-mongo-template/lists"}