mongohelper

package module
Version: v0.0.0-...-bdd347a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2020 License: MIT Imports: 10 Imported by: 0

README

Mongo Helper

A simple wrapper and concentrator that helps to deal with connection and to recover from unexpected disconnection

Made over MongoDB Official Driver
GitHub GitHub Go Report Card
Check the docs here

Examples
package main

import (
	"fmt"
	"github.com/go-acme/lego/log"
	"github.com/miguelpragier/mongohelper"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"time"
)

const (
	testDB         = `mongohelper`
	testCollection = `testsuite`
)

var testConnectionString = fmt.Sprintf("mongodb://127.0.0.1:27017/%s", testDB)

type testDocStruct struct {
	ID   primitive.ObjectID `bson:"_id,omitempty"`
	Name string             `bson:"name,omitempty"`
	TS   time.Time          `bson:"ts,omitempty"`
	N    int                `bson:"n,omitempty"`
}

func main() {
	const (
        appName = "my app"
		connTimeoutSeconds         = 10 // Time to wait for the first connection
		execTimeoutSeconds         = 10 // Time to wait for execution
		reconnTimeoutSeconds       = 10 // Time between reconnection attempts
		reconnAttemptsLimit        = 0  // Top limit for (re)connection attempts
		reconnAttemptsLimitMinutes = 5  // limit time trying to reconnect
		insistOnFailure            = false
		logDebugMessages           = true
	)

	var (
		mdb             mongohelper.Link
		lastInsertedOID primitive.ObjectID
	)

	log.Println("Connecting db...")

	if _m, err := mongohelper.New(mongohelper.OptionsNew(appName,testConnectionString,connTimeoutSeconds, execTimeoutSeconds, reconnTimeoutSeconds, reconnAttemptsLimit, reconnAttemptsLimitMinutes, insistOnFailure, logDebugMessages)); err != nil {
		log.Fatal(err)
	} else {
		mdb = *_m
	}

	x := testDocStruct{
		ID:   primitive.NewObjectID(),
		Name: "testing insertone",
		TS:   time.Now(),
		N:    125,
	}

	log.Println("Inserting one doc")

	if s, err := mdb.InsertOne(testDB, testCollection, &x); err != nil {
		log.Println(err)
	} else {
		log.Printf("inserted oID: %s\n", s)
	}

	var a []interface{}

	for i := 0; i < 100; i++ {
		x := testDocStruct{
			ID:   primitive.NewObjectID(),
			Name: fmt.Sprintf("test #%d", i),
			TS:   time.Now().Add(time.Duration(i) * time.Hour),
			N:    i * 2,
		}

		a = append(a, x)

		lastInsertedOID = x.ID
	}

	log.Println("Inserting many doc")

	if ioids, err := mdb.InsertMany(testDB, testCollection, a); err != nil {
		log.Println(err)
	} else {
		log.Printf("inserted oIDs: %d\n", len(ioids))
	}

	log.Println("testing .CountDocs() with empty filter")

	if n, err := mdb.CountDocs(testDB, testCollection, bson.M{}); err != nil {
		log.Println(err)
	} else {
		log.Printf("found %d docs\n", n)
	}

	log.Println("testing .CountDocs() with ObjectId filter")

	if n, err := mdb.CountDocs(testDB, testCollection, bson.M{"_id": lastInsertedOID}); err != nil {
		log.Println(err)
	} else {
		log.Printf("searched oID %s and found %d docs\n", lastInsertedOID.Hex(), n)
	}

	log.Println("updating one doc")

	if n, err := mdb.UpdateOne(testDB, testCollection, bson.M{"_id": lastInsertedOID}, bson.M{"$set": bson.M{"xyz": "abc"}}); err != nil {
		log.Println(err)
	} else {
		log.Printf("%d doc updated\n", n)
	}

	var docsToDelete int64

	log.Println("updating many docs")

	if n, err := mdb.UpdateMany(testDB, testCollection, bson.M{"n": 8}, bson.M{"$set": bson.M{"name": "delete me!"}}); err != nil {
		log.Println(err)
	} else {
		docsToDelete = n

		log.Printf("updated docs flagged to be deleted: %d\n", docsToDelete)
	}

	log.Println("deleting one doc")

	if n, err := mdb.DeleteOne(testDB, testCollection, bson.M{"xyz": "abc"}); err != nil {
		log.Println(err)
	} else {
		log.Printf("delete %d document %s\n", n, lastInsertedOID.Hex())
	}

	log.Println("deleting many docs")

	if n, err := mdb.DeleteMany(testDB, testCollection, bson.M{"name": "delete me!"}); err != nil {
		log.Println(err)
	} else {
		log.Printf("deleted docs %d\n", n)

		if n != docsToDelete {
			log.Printf("expected deleteable docs: %d\n", docsToDelete)
		}
	}
}

Documentation

Index

Constants

View Source
const (
	// SecondsBetweenAttemptsMin When retrying connection, minimum time betwwen attempts
	SecondsBetweenAttemptsMin uint = 5
	// ConnectionTimeoutSecondsDefault limits the time waiting from a connection request
	ConnectionTimeoutSecondsDefault uint = 30
	// ConnectionTimeoutSecondsMin limits the minimum time waiting from a connection request
	ConnectionTimeoutSecondsMin uint = 3
	// ExecutionTimeoutSecondsDefault limits the time waiting from an execution request
	ExecutionTimeoutSecondsDefault uint = 10
	// ExecutionTimeoutSecondsMin limits the minimum time waiting from an execution request
	ExecutionTimeoutSecondsMin uint = 1
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Link struct {
	// contains filtered or unexported fields
}

Link is a concentrator wrapper for mongodb client

func New

func New(opts *Options) (*Link, error)

New returns an instance of mongohelper, ugins given options It the connection conditions are ok, it comes alerady connected and tested with .Ping() You may prefer to create the options with .OptionsNew() function

func (Link) Collection

func (l Link) Collection(database, collection string) (*mongo.Collection, error)

Collection returns a collection from the target database

func (*Link) CountDocs

func (l *Link) CountDocs(database, collection string, filter interface{}) (int64, error)

CountDocs wraps the mongo.Database.Collection.CountDocuments() method It returns the number of documents in the collection and an error

The filter parameter must be a document and can be used to select which documents contribute to the count. It cannot be nil. An empty document (e.g. bson.D{}) should be used to count all documents in the collection. This will result in a full collection scan.

func (*Link) DeleteMany

func (l *Link) DeleteMany(database, collection string, filter interface{}) (int64, error)

DeleteMany wraps the mongo.Database.Collection.DeleteMany() method It returns the number of affected records and an error

func (*Link) DeleteOne

func (l *Link) DeleteOne(database, collection string, filter interface{}) (int64, error)

DeleteOne wraps the mongo.Database.Collection.DeleteOne() method It returns the number of affected records and an error

func (*Link) Disconnect

func (l *Link) Disconnect()

Disconnect closes the client connection with database

func (*Link) Find

func (l *Link) Find(database, collection string, filter interface{}, dest interface{}) error

Find cs wraps the mongo.Database.Collection.Find() method It returns a Cursor over the matching documents in the collection.

The filter parameter must be a document containing query operators and can be used to select which documents are included in the result. An empty document (e.g. bson.D{}) should be used to include all documents.

func (*Link) FindOne

func (l *Link) FindOne(database, collection string, filter interface{}, dest interface{}) error

FindOne wraps the mongo.Database.Collection.FindOne() method It returns a SingleResult for one document in the collection.

The filter parameter must be a document containing query operators and can be used to select the document to be returned. If the filter does not match any documents, a SingleResult with an error set to ErrNoDocuments will be returned. If the filter matches multiple documents, one will be selected from the matched set.

func (*Link) InsertMany

func (l *Link) InsertMany(database, collection string, document []interface{}) ([]string, error)

InsertMany wraps the mongo.Database.Collection.InsertMany() method It returns an array with generated ObjectIDs and an error

func (*Link) InsertOne

func (l *Link) InsertOne(database, collection string, document interface{}) (string, error)

InsertOne wraps the mongo.Database.Collection.InsertOne() method It returns the generated ObjectId and an error

func (*Link) UpdateMany

func (l *Link) UpdateMany(database, collection string, filter, update interface{}) (int64, error)

UpdateMany wraps the mongo.Database.Collection.UpdateMany() method It returns the number of matched records and an error The filter parameter must be a document containing query operators and can be used to select the documents to be updated. It cannot be nil. If the filter does not match any documents, the operation will succeed and an UpdateResult with a MatchedCount of 0 will be returned.

The update parameter must be a document containing update operators (https://docs.mongodb.com/manual/reference/operator/update/) and can be used to specify the modifications to be made to the selected documents. It cannot be nil or empty.

func (*Link) UpdateOne

func (l *Link) UpdateOne(database, collection string, filter, update interface{}) (int64, error)

UpdateOne wraps the mongo.Database.Collection.UpdateOne() method It returns the number of matched records and an error The filter parameter must be a document containing query operators and can be used to select the document to be updated. It cannot be nil. If the filter does not match any documents, the operation will succeed and an UpdateResult with a MatchedCount of 0 will be returned. If the filter matches multiple documents, one will be selected from the matched set and MatchedCount will equal 1.

The update parameter must be a document containing update operators (https://docs.mongodb.com/manual/reference/operator/update/) and can be used to specify the modifications to be made to the selected document. It cannot be nil or empty.

type Options

type Options struct {
	// contains filtered or unexported fields
}

Options contains all necessary parameters to connect and mantain database client

func OptionsNew

func OptionsNew(appName, connectionString string, connectTimeoutInSeconds, execTimeoutInSeconds, reconnectTimeInSeconds, reconnecAttemptsLimit, reconnectAttemptsLimitMinutes uint, insistOnFail, logMessages bool) *Options

OptionsNew returns a pointer to mongohelper.Options instance. Why a pointer? In this case is because you can send nil instead, and the engine provides default values. connString, a well-formed URI for mongodb. Attention: is mandatory connectTimeoutInSeconds is quite obvious reconnectTimeInSeconds Seconds btween each connection attempt reconnecAttemptsLimit maximum number of (re)connection attempts or 0 for infinite reconnectAttemptsLimitMinutes maximum time ( in minutes ) trying to (re)connect or 0 for infinite insistOnFail If can't connect on first attempt, if should retry logMessages if true allow the engine to print out log messages to stdout

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
t or T : Toggle theme light dark auto
y or Y : Canonical URL