Provides helpers on top of 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
returnsmongo.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 toWithAutoFlush
sets auto flush duration
-
PrepSort
- prepares sort objectbson.D
from strings like"a,-b"
-
PrepIndex
- prepares index objectdriver.IndexModel
from strings like"a,-b"
mongo.MakeTestConnection
createsmongo.Client
andmongo.Collection
for url defined in envMONGO_TEST
. If not definedmongodb://mongo:27017
used. By default it will use random connection with prefixtest_
intest
DB.MakeTestConnectionWithColl
createsmongo.Client
andmongo.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.