mongoifc
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
mongoifc
The Interfaces for the MongoDB driver
Versioning Policy
Themongoifc code is stabilized, so now the version will match the version of the MongoDB driver sincev1.8.0.
In case of need for bug fixes inmongoifc, the version will be in this formatv1.8.1+N, wherev1.8.1 is theversion of MongoDB driver andN is a patch ofmongoifc. The new version for changes in README.md, tests, examples,GitHub workflows is not required.
‼Important
It is not a simple drop in replacement because of the limitations in Go. You should rewrite your code to use thislibrary instead of mongo driver.
conn := mongoifc.Connect(...)instead of
conn := mongo.Connect(...)or if you have a special code that returns the mongo object then you need to use one ofWrap functions to wrapthemongo.Client ormongo.Database ormongo.Collection ormongo.Session objects:
orig := mongo.Connect(...)...conn := mongoifc.WrapClient(orig)or
func GetTenantDB(ctx context.Context, tenantID, dbName string) (*mongo.Database, error) {// a code that returns a special database for a given tenant and database name}...orig, err := GetTenantDB(ctx, tenant, "users")if err != nil {...}db = mongoifc.WrapDatabase(orig)Now let's dig a bit into the limitations. Assume that you have a function to return a list of admin users, and yourewrote it usingmongoifc:
package users// Original: func GetAdmins(ctx context.Context, db *mongo.Database) ([]*User, error)func GetAdmins(ctx context.Context, db mongoifc.Database) ([]User, error) {var users []Usercur, err := db.Collection(UsersCollection).Find(ctx, User{Active: true,IsAdmin: true,})if err != nil {return nil, err}if err := cur.All(ctx, &users); err != nil {return nil, err}return users, err}and if you pass an object of*mongo.Database type instead ofmongoifc.Database
conn, _ := mongo.Connect(context.Background(), ...)db := conn.Database(...)users.GetAdmins(context.Background(), db)then compilation fails with such error:
cannot use db (type *mongo.Database) as type mongoifc.Database in argument to simple.GetAdmins: *mongo.Database does not implement mongoifc.Database (wrong type for Aggregate method) have Aggregate(context.Context, interface {}, ...*"go.mongodb.org/mongo-driver/mongo/options".AggregateOptions) (*mongo.Cursor, error) want Aggregate(context.Context, interface {}, ...*"go.mongodb.org/mongo-driver/mongo/options".AggregateOptions) (mongoifc.Cursor, error)This is the main reason of wrapping the original objects and using themongoifc instead.
Wrapped Interfaces
- ChangeStream:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#ChangeStream
- Client:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Client
- ClientEncryption:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#ClientEncryption
- Collection:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Collection
- Cursor:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Cursor
- Database:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Database
- IndexView:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#IndexView
- Session:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Session
- SessionContext:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SessionContext
- SingleResult:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SingleResult
Mocks
Themocks folder contains the mocks generated bymockeryandgomock tools.
The examples of how to use the mocks can be found in theexamples folder or check any of the*_test.go files aswell.
Simple Example
user workflow
- Create 4 users, with two admins, using
InsertManyfunction. - Get the admin users only using
Findfunction - Delete all users using
DeleteManyfunction
- users.go is a file with a set of functions, like:
Createto create the users usingInsertManyDeleteto delete the users by given IDsGetAdminsto return the list of admin users
- users_test.go is a file with
TestUsersWorkflowunit tests:mockerytests the workflow usingmockerymocksgomocktests the workflow usinggomockmocksdockertests the workflow using real mongo database run by docker
collection workflow
- Create a collection with random name.
- Check that the collection exists.
- Check that another collection does not exist.
- Drop collection.
- Check that the original collection does not exist.
- collections.go is a file with a set of functions, like:
CreateCollectionto create a collection usingCreateCollectionDropCollectionto delete a collection by given nameCollectionExiststo check that a collection exists
- collections_test.go is a file with
TestCollectionsWorkflowunit tests:mockerytests the workflow usingmockerymocksgomocktests the workflow usinggomockmocksdockertests the workflow using real mongo database run by docker
Documentation¶
Index¶
- func UnWrapClient(cl Client) *mongo.Client
- func UnWrapCollection(co Collection) *mongo.Collection
- func UnWrapDatabase(db Database) *mongo.Database
- func UnWrapSession(ss Session) mongo.Session
- func WithSession(ctx context.Context, sess Session, fn func(sc SessionContext) error) error
- type ChangeStream
- type Client
- type ClientEncryption
- type Collection
- type Cursor
- type Database
- type IndexView
- type SearchIndexView
- type Session
- type SessionContext
- type SingleResult
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
funcUnWrapClient¶added inv1.0.0
UnWrapClient returns original mongo.Client
funcUnWrapCollection¶added inv1.8.2
func UnWrapCollection(coCollection) *mongo.Collection
UnWrapCollection returns original mongo.Collection
funcUnWrapDatabase¶added inv1.8.2
UnWrapDatabase returns original mongo.Database
funcUnWrapSession¶added inv1.8.2
UnWrapSession returns original mongo.Session
funcWithSession¶
WithSession is a wrapper for `mongo.WithSession` function to call then `mongo.WithSession` functionDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#WithSession
Types¶
typeChangeStream¶
type ChangeStream interface {Current()bson.RawClose(ctxcontext.Context)errorDecode(val interface{})errorErr()errorID()int64Next(ctxcontext.Context)boolResumeToken()bson.RawSetBatchSize(sizeint32)TryNext(ctxcontext.Context)bool}ChangeStream is an interface for `mongo.ChangeStream` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#ChangeStream
typeClient¶
type Client interface {Connect(ctxcontext.Context)errorDatabase(namestring, opts ...*options.DatabaseOptions)DatabaseDisconnect(ctxcontext.Context)errorListDatabaseNames(ctxcontext.Context,filter interface{},opts ...*options.ListDatabasesOptions,) ([]string,error)ListDatabases(ctxcontext.Context,filter interface{},opts ...*options.ListDatabasesOptions,) (mongo.ListDatabasesResult,error)NumberSessionsInProgress()intPing(ctxcontext.Context, rp *readpref.ReadPref)errorStartSession(opts ...*options.SessionOptions) (Session,error)Timeout() *time.DurationUseSession(ctxcontext.Context,fn func(scSessionContext)error,)errorUseSessionWithOptions(ctxcontext.Context,opts *options.SessionOptions,fn func(scSessionContext)error,)errorWatch(ctxcontext.Context,pipeline interface{},opts ...*options.ChangeStreamOptions,) (ChangeStream,error)}Client is an interface for `mongo.Client` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Client
funcConnect¶
Connect is a wrapper for `mongo.Connect` function to return the object as `Client` interfaceDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Connect
funcNewClientdeprecated
func NewClient(opts ...*options.ClientOptions) (Client,error)
NewClient is a wrapper for `mongo.NewClient` function to return the object as `Client` interfaceDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#NewClient
Deprecated: UseConnect instead.
funcWrapClient¶
WrapClient returns an instance of Client interface for given mongo.Client object
typeClientEncryption¶added inv1.13.0
type ClientEncryption interface {AddKeyAltName(ctxcontext.Context,idprimitive.Binary,keyAltNamestring,)SingleResultClose(ctxcontext.Context)errorCreateDataKey(ctxcontext.Context,kmsProviderstring,opts ...*options.DataKeyOptions,) (primitive.Binary,error)CreateEncryptedCollection(ctxcontext.Context,dbDatabase,collstring,createOpts *options.CreateCollectionOptions,kmsProviderstring,masterKey interface{},) (Collection,bson.M,error)Decrypt(ctxcontext.Context, valprimitive.Binary) (bson.RawValue,error)DeleteKey(ctxcontext.Context, idprimitive.Binary) (*mongo.DeleteResult,error)Encrypt(ctxcontext.Context,valbson.RawValue,opts ...*options.EncryptOptions,) (primitive.Binary,error)EncryptExpression(ctxcontext.Context,expr interface{},result interface{},opts ...*options.EncryptOptions,)errorGetKey(ctxcontext.Context, idprimitive.Binary)SingleResultGetKeyByAltName(ctxcontext.Context, keyAltNamestring)SingleResultGetKeys(ctxcontext.Context) (Cursor,error)RemoveKeyAltName(ctxcontext.Context,idprimitive.Binary,keyAltNamestring,)SingleResultRewrapManyDataKey(ctxcontext.Context,filter interface{},opts ...*options.RewrapManyDataKeyOptions,) (*mongo.RewrapManyDataKeyResult,error)}ClientEncryption is an interface for `mongo.ClientEncryption` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#ClientEncryption
funcNewClientEncryption¶added inv1.13.0
func NewClientEncryption(keyVaultClientClient, opts ...*options.ClientEncryptionOptions) (ClientEncryption,error)
typeCollection¶
type Collection interface {Aggregate(ctxcontext.Context, pipeline interface{}, opts ...*options.AggregateOptions) (Cursor,error)BulkWrite(ctxcontext.Context,models []mongo.WriteModel,opts ...*options.BulkWriteOptions,) (*mongo.BulkWriteResult,error)Clone(opts ...*options.CollectionOptions) (Collection,error)CountDocuments(ctxcontext.Context, filter interface{}, opts ...*options.CountOptions) (int64,error)Database()DatabaseDeleteMany(ctxcontext.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult,error)DeleteOne(ctxcontext.Context, filter interface{}, opts ...*options.DeleteOptions) (*mongo.DeleteResult,error)Distinct(ctxcontext.Context,fieldNamestring,filter interface{},opts ...*options.DistinctOptions,) ([]interface{},error)Drop(ctxcontext.Context)errorEstimatedDocumentCount(ctxcontext.Context, opts ...*options.EstimatedDocumentCountOptions) (int64,error)Find(ctxcontext.Context, filter interface{}, opts ...*options.FindOptions) (Cursor,error)FindOne(ctxcontext.Context, filter interface{}, opts ...*options.FindOneOptions)SingleResultFindOneAndDelete(ctxcontext.Context, filter interface{}, opts ...*options.FindOneAndDeleteOptions)SingleResultFindOneAndReplace(ctxcontext.Context,filter interface{},replacement interface{},opts ...*options.FindOneAndReplaceOptions,)SingleResultFindOneAndUpdate(ctxcontext.Context,filter interface{},update interface{},opts ...*options.FindOneAndUpdateOptions,)SingleResultIndexes()IndexViewInsertMany(ctxcontext.Context,documents []interface{},opts ...*options.InsertManyOptions,) (*mongo.InsertManyResult,error)InsertOne(ctxcontext.Context,document interface{},opts ...*options.InsertOneOptions,) (*mongo.InsertOneResult,error)Name()stringReplaceOne(ctxcontext.Context,filter interface{},replacement interface{},opts ...*options.ReplaceOptions,) (*mongo.UpdateResult,error)SearchIndexes()SearchIndexViewUpdateByID(ctxcontext.Context,id interface{},update interface{},opts ...*options.UpdateOptions,) (*mongo.UpdateResult,error)UpdateMany(ctxcontext.Context,filter interface{},update interface{},opts ...*options.UpdateOptions,) (*mongo.UpdateResult,error)UpdateOne(ctxcontext.Context,filter interface{},update interface{},opts ...*options.UpdateOptions,) (*mongo.UpdateResult,error)Watch(ctxcontext.Context, pipeline interface{}, opts ...*options.ChangeStreamOptions) (ChangeStream,error)}Collection is an interface for `mongo.Collection` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Collection
funcWrapCollection¶added inv1.8.2
func WrapCollection(co *mongo.Collection)Collection
WrapCollection returns an instance of Collection interface for given mongo.Collection object
typeCursor¶
type Cursor interface {Current()bson.RawAll(ctxcontext.Context, results interface{})errorClose(ctxcontext.Context)errorDecode(val interface{})errorErr()errorID()int64Next(ctxcontext.Context)boolRemainingBatchLength()intSetBatchSize(batchSizeint32)SetComment(comment interface{})SetMaxTime(durtime.Duration)TryNext(ctxcontext.Context)bool}Cursor is an interface for `mongo.Cursor` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Cursor
funcNewCursorFromDocuments¶added inv1.9.0
func NewCursorFromDocuments(documents []interface{}, errerror, registry *bsoncodec.Registry) (Cursor,error)NewCursorFromDocuments is a wrapper for NewCursorFromDocuments function of the mongodb to return Cursorhttps://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#NewCursorFromDocuments
typeDatabase¶
type Database interface {Aggregate(ctxcontext.Context, pipeline interface{}, opts ...*options.AggregateOptions) (Cursor,error)Client()ClientCollection(namestring, opts ...*options.CollectionOptions)CollectionCreateCollection(ctxcontext.Context, namestring, opts ...*options.CreateCollectionOptions)errorCreateView(ctxcontext.Context,viewName, viewOnstring,pipeline interface{},opts ...*options.CreateViewOptions,)errorDrop(ctxcontext.Context)errorListCollectionNames(ctxcontext.Context,filter interface{},opts ...*options.ListCollectionsOptions,) ([]string,error)ListCollectionSpecifications(ctxcontext.Context,filter interface{},opts ...*options.ListCollectionsOptions,) ([]*mongo.CollectionSpecification,error)ListCollections(ctxcontext.Context, filter interface{}, opts ...*options.ListCollectionsOptions) (Cursor,error)Name()stringReadConcern() *readconcern.ReadConcernReadPreference() *readpref.ReadPrefRunCommand(ctxcontext.Context, runCommand interface{}, opts ...*options.RunCmdOptions)SingleResultRunCommandCursor(ctxcontext.Context, runCommand interface{}, opts ...*options.RunCmdOptions) (Cursor,error)Watch(ctxcontext.Context,pipeline interface{},opts ...*options.ChangeStreamOptions,) (ChangeStream,error)WriteConcern() *writeconcern.WriteConcern}Database is an interface for `mongo.Database` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Database
funcWrapDatabase¶added inv1.8.2
WrapDatabase returns an instance of Database interface for given mongo.Database object
typeIndexView¶
type IndexView interface {CreateMany(ctxcontext.Context, models []mongo.IndexModel, opts ...*options.CreateIndexesOptions) ([]string,error)CreateOne(ctxcontext.Context, modelmongo.IndexModel, opts ...*options.CreateIndexesOptions) (string,error)DropAll(ctxcontext.Context, opts ...*options.DropIndexesOptions) (bson.Raw,error)DropOne(ctxcontext.Context, namestring, opts ...*options.DropIndexesOptions) (bson.Raw,error)DropOneWithKey(ctxcontext.Context,keySpecDocument interface{},opts ...*options.DropIndexesOptions,) (bson.Raw,error)List(ctxcontext.Context, opts ...*options.ListIndexesOptions) (Cursor,error)ListSpecifications(ctxcontext.Context, opts ...*options.ListIndexesOptions) ([]*mongo.IndexSpecification,error)}IndexView is an interface for `mongo.IndexView` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#IndexView
typeSearchIndexView¶added inv1.13.0
type SearchIndexView interface {CreateMany(ctxcontext.Context,models []mongo.SearchIndexModel,opts ...*options.CreateSearchIndexesOptions,) ([]string,error)CreateOne(ctxcontext.Context,modelmongo.SearchIndexModel,opts ...*options.CreateSearchIndexesOptions,) (string,error)DropOne(ctxcontext.Context,namestring,opts ...*options.DropSearchIndexOptions,)errorList(ctxcontext.Context,searchIdxOpts *options.SearchIndexesOptions,opts ...*options.ListSearchIndexesOptions,) (Cursor,error)UpdateOne(ctxcontext.Context,namestring,definition interface{},opts ...*options.UpdateSearchIndexOptions,)error}SearchIndexView is an interface for `mongo.SearchIndexView` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SearchIndexView
typeSession¶
type Session interface {StartTransaction(opts ...*options.TransactionOptions)errorAbortTransaction(ctxcontext.Context)errorCommitTransaction(ctxcontext.Context)errorWithTransaction(ctxcontext.Context,fn func(scSessionContext) (interface{},error),opts ...*options.TransactionOptions,) (interface{},error)EndSession(ctxcontext.Context)ClusterTime()bson.RawOperationTime() *primitive.TimestampClient()ClientID()bson.RawAdvanceClusterTime(bson.Raw)errorAdvanceOperationTime(*primitive.Timestamp)error}Session is an interface for `mongo.Session` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#Session
funcSessionFromContext¶added inv1.10.1
SessionFromContext for `mongo.SessionFromContext`Documentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SessionFromContext
funcWrapSession¶added inv1.8.2
WrapSession returns an instance of Session interface for given mongo.Session object
typeSessionContext¶added inv1.0.0
SessionContext is an interface emulates `mongo.SessionContext`Documentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SessionContext
funcNewSessionContext¶added inv1.10.1
func NewSessionContext(ctxcontext.Context, sessSession)SessionContext
NewSessionContext is wrapper for `mongo.NewSessionContext`Documentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#NewSessionContext
typeSingleResult¶
type SingleResult interface {Decode(v interface{})errorDecodeBytes() (bson.Raw,error)Err()errorRaw() (bson.Raw,error)}SingleResult is an interface for `mongo.SingleResult` structureDocumentation:https://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#SingleResult
funcNewSingleResultFromDocument¶added inv1.9.0
func NewSingleResultFromDocument(document interface{}, errerror, registry *bsoncodec.Registry)SingleResultNewSingleResultFromDocument is a wrapper for NewSingleResultFromDocument function of the mongodbto return SingleResulthttps://pkg.go.dev/go.mongodb.org/mongo-driver/mongo#NewSingleResultFromDocument