Categorygithub.com/go-pkgz/mongo/v2
modulepackage
2.2.1
Repository: https://github.com/go-pkgz/mongo.git
Documentation: pkg.go.dev

# README

Mongo Build Status Go Report Card Coverage Status

Provides helpers on top of mongo-go-driver

Version 2, for the official mongo-go-driver

note: version 1 (mgo based) is deprecated

  • Install and update - go get -u github.com/go-pkgz/mongo/v2

  • Connect - Connects with mongo url and return mongo client. Supports extra url params to pass a set of custom values in the url, for example "mongodb://127.0.0.1:27017/test?debug=true&foo=bar. Connect returns mongo.Client as well as the map with all extra key/values. After connect call it also tries to ping the mongo server.

    opts := options.Client().SetAppName("test-app")
    m, params err := Connect(ctx, opts, "mongodb://127.0.0.1:27017/test?debug=true&name=abcd", "debug", "name")
    if err != nil {
        panic("can't make mongo server")
    }
    log.Printf("%+v", params) // prints {"debug":true, "name":"abcd"} 
  • BufferedWriter implements buffered writer to mongo. Write method caching internally till it reached buffer size. Flush methods can be called manually at any time.

    • WithCollection sets collection name to write to
    • WithAutoFlush sets auto flush duration
  • PrepSort - prepares sort object bson.D from strings like "a,-b"

  • PrepIndex - prepares index object driver.IndexModel from strings like "a,-b"

Testing

  • mongo.MakeTestConnection creates mongo.Client and mongo.Collection for url defined in env MONGO_TEST. If not definedmongodb://mongo:27017 used. By default it will use random connection with prefix test_ in test DB.
  • MakeTestConnectionWithColl creates mongo.Client and mongo.Collection with a custom collection name.

Both methods return mongo.Client and mongo.Collection which can be used for testing. It also returns teardown func to clean mongo after the test.

# Functions

Bind request json body from io.Reader to bson record.
Connect to mongo url and return client.
MakeTestConnection connects to MONGO_TEST url or "mongo" host (in no env) and returns new connection.
MakeTestConnectionWithColl connects to MONGO_TEST url or "mongo" host (in no env) and returns new connection.
NewBufferedWriter makes batch writer for given size and connection.
PrepIndex prepares index params for mongo driver and returns IndexModel.
PrepSort prepares sort params for mongo driver and returns bson.D Input string provided as [+|-]field1,[+|-]field2,[+|-]field3..
SecretsMongoUrls retrieves passwords from mongo urls.

# Structs

BufferedWriterMongo collects records in local buffer and flushes them as filled.

# Interfaces

BufferedWriter defines interface for writes and flush.