mongodb

package
v2.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 2, 2021 License: MIT Imports: 15 Imported by: 1

README

Mongo Driver

This intended to be an abstraction that can encapsulate the mongo db and the document db operations. All the functionalities are supposed to be done via a common interface.
This interface is responsible for connection handling as well as the querying.

Running tests

Env Setup

test user is expected to be configured with access to testDb containing testCollection.

Against MongoDB

Bring up the mongodb test instance for testing the mongo db suite.

Against DocumentDB

Forward the documentDb cluster to local and then run the test suites. This does not work against the document db instance being forwarded.

dp ssh develop publishing 4 -- -L 27017:<document-db-cluster-url>:27017

Documentation

Index

Constants

View Source
const (
	LastUpdatedKey     = "last_updated"
	UniqueTimestampKey = "unique_timestamp"
)

keep these in sync with Timestamps tags below

Variables

This section is empty.

Functions

func HasRemovedRecords

func HasRemovedRecords(deleteResult *CollectionDeleteResult) bool

returns true if a remove operation has remove at least one record

func HasUpdatedOrUpserted

func HasUpdatedOrUpserted(updateResult *CollectionUpdateResult) bool

returns true if a update operation updated or upserted a record

func IsErrNoDocumentFound

func IsErrNoDocumentFound(err error) bool

func IsServerErr

func IsServerErr(err error) bool

func NewErrNoDocumentFoundError

func NewErrNoDocumentFoundError(msg string, err error) error

func WithLastUpdatedUpdate

func WithLastUpdatedUpdate(updateDoc bson.M) (bson.M, error)

WithLastUpdatedUpdate adds last_updated to updateDoc

func WithNamespacedLastUpdatedUpdate

func WithNamespacedLastUpdatedUpdate(updateDoc bson.M, prefixes []string) (newUpdateDoc bson.M, err error)

WithNamespacedLastUpdatedUpdate adds unique timestamp to updateDoc

func WithNamespacedUniqueTimestampQuery

func WithNamespacedUniqueTimestampQuery(queryDoc bson.M, timestamps []primitive.Timestamp, prefixes []string) bson.M

WithNamespacedUniqueTimestampQuery adds unique timestamps to queryDoc sub-docs

func WithNamespacedUniqueTimestampUpdate

func WithNamespacedUniqueTimestampUpdate(updateDoc bson.M, prefixes []string) (newUpdateDoc bson.M, err error)

WithNamespacedUniqueTimestampUpdate adds unique timestamp to updateDoc

func WithNamespacedUpdates

func WithNamespacedUpdates(updateDoc bson.M, prefixes []string) (bson.M, error)

WithNamespacedUpdates adds all timestamps to updateDoc

func WithUniqueTimestampQuery

func WithUniqueTimestampQuery(queryDoc bson.M, timestamp primitive.Timestamp) bson.M

WithUniqueTimestampQuery adds unique timestamp to queryDoc

func WithUniqueTimestampUpdate

func WithUniqueTimestampUpdate(updateDoc bson.M) (bson.M, error)

WithUniqueTimestampUpdate adds unique timestamp to updateDoc

func WithUpdates

func WithUpdates(updateDoc bson.M) (bson.M, error)

WithUpdates adds all timestamps to updateDoc

Types

type Collection

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

func NewCollection

func NewCollection(collection *mongo.Collection) *Collection

func (*Collection) Aggregate

func (c *Collection) Aggregate(pipeline interface{}) *Cursor

Aggreate start a pipeline operation

func (*Collection) Find

func (c *Collection) Find(query interface{}) *Find

Find returns a Find interface which can be used to either refine the criteria or retrieve a cursor

func (*Collection) FindOne

func (c *Collection) FindOne(ctx context.Context, filter interface{}, result interface{}) error

FindOne locates a single document

func (*Collection) Insert

func (c *Collection) Insert(ctx context.Context, documents []interface{}) (*CollectionInsertResult, error)

Insert adds a number of documents

func (*Collection) InsertOne

func (c *Collection) InsertOne(ctx context.Context, document interface{}) (*CollectionInsertOneResult, error)

InsertOne creates a single record

func (*Collection) Must

func (c *Collection) Must() *Must

func (*Collection) Remove

func (c *Collection) Remove(ctx context.Context, selector interface{}) (*CollectionDeleteResult, error)

Remove deletes records based on the provided selector

func (*Collection) RemoveId

func (c *Collection) RemoveId(ctx context.Context, id interface{}) (*CollectionDeleteResult, error)

RemoveId deletes record based on the id selector

func (*Collection) Update

func (c *Collection) Update(ctx context.Context, selector interface{}, update interface{}) (*CollectionUpdateResult, error)

Update modifies records located by a provided selector

func (*Collection) UpdateId

func (c *Collection) UpdateId(ctx context.Context, id interface{}, update interface{}) (*CollectionUpdateResult, error)

UpdateId modifies records located by a provided Id selector

func (*Collection) Upsert

func (c *Collection) Upsert(ctx context.Context, selector interface{}, update interface{}) (*CollectionUpdateResult, error)

Upsert creates or updates records located by a provided selector

func (*Collection) UpsertId

func (c *Collection) UpsertId(ctx context.Context, id interface{}, update interface{}) (*CollectionUpdateResult, error)

UpsertId creates or updates records located by a provided Id selector

type CollectionDeleteResult

type CollectionDeleteResult struct {
	DeletedCount int // The number of records deleted
}

type CollectionInsertOneResult

type CollectionInsertOneResult struct {
	InsertedId interface{} // Id of the document inserted
}

CollectionInsertOneResult is the result type return from InsertOne

type CollectionInsertResult

type CollectionInsertResult struct {
	InsertedIds []interface{} // inserted Ids
}

CollectionInsertResult is the result type returned from Insert

type CollectionUpdateResult

type CollectionUpdateResult struct {
	MatchedCount  int         // The number of documents matched by the filter.
	ModifiedCount int         // The number of documents modified by the operation.
	UpsertedCount int         // The number of documents upserted by the operation.
	UpsertedID    interface{} // The _id field of the upserted document, or nil if no upsert was done.
}

CollectionUpdateResult is the result type returned from UpdateOne, UpdateMany, and ReplaceOne operations.

type CreateAggregateCursor

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

CreateAggreateCursor creates a cursor used with aggregation

type CreateCursor

type CreateCursor interface {
	// contains filtered or unexported methods
}

CreateCursor interface to create a unique cursor

type CreateFindCursor

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

CreateFindCursor creates a find cursor

type Cursor

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

func (*Cursor) All

func (cursor *Cursor) All(ctx context.Context, results interface{}) error

All returns all the results for this cursor

func (*Cursor) Close

func (cursor *Cursor) Close(ctx context.Context) error

Close closes a cursor

func (*Cursor) Err

func (cursor *Cursor) Err() error

Err returns the last error which occured for this cursor

func (*Cursor) Next

func (cursor *Cursor) Next(ctx context.Context) bool

Next returns the next available record which must be available

func (*Cursor) TryNext

func (cursor *Cursor) TryNext(ctx context.Context) bool

TryNext trys to retrieve the next available record

type ErrDisconnect

type ErrDisconnect struct {
	MongoError
}

type ErrNoDocumentFound

type ErrNoDocumentFound struct {
	MongoError
}

type ErrServerError

type ErrServerError struct {
	MongoError
}

type ErrTimeout

type ErrTimeout struct {
	MongoError
}

type Find

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

func (*Find) Count

func (find *Find) Count(ctx context.Context) (int, error)

Count the number of records which match the find query

func (*Find) Distinct

func (find *Find) Distinct(ctx context.Context, fieldName string) ([]interface{}, error)

Distinct return only distinct records

func (*Find) Find

func (find *Find) Find(query interface{}) *Find

Find set the find query

func (*Find) Iter

func (find *Find) Iter() *Cursor

Iter return a cursor to iterate through the results

func (*Find) IterAll

func (find *Find) IterAll(ctx context.Context, results interface{}) error

IterAll return all the results for this query, you do not need to close the cursor after this call

func (*Find) Limit

func (find *Find) Limit(limit int) *Find

Limit set the max number of records to retrieve

func (*Find) One

func (find *Find) One(ctx context.Context, val interface{}) error

Find a record which matches the find criteria Current FindOptions are limited to what is used: Sort, Skip, Projection Other exhaustive list of options are: AllowPartialResults,BatchSize,Collation, Comment,CursorType,Hint,Max, MaxAwaitTime, MaxTime ,Min, NoCursorTimeout,OplogReplay,ReturnKey,ShowRecordID, Snapshot, ref: https://github.com/mongodb/mongo-go-driver/blob/master/mongo/options/findoptions.go#L306

func (*Find) Select

func (find *Find) Select(projection interface{}) *Find

Select specifies the fields to return

func (*Find) Skip

func (find *Find) Skip(skip int) *Find

Skip set the number of records to skip when the query is run

func (*Find) Sort

func (find *Find) Sort(sort interface{}) *Find

Sort set the sort criteria

type Graceful

type Graceful interface {
	// contains filtered or unexported methods
}

Graceful represents an interface to the shutdown method

type MongoConnection

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

func NewMongoConnection

func NewMongoConnection(client *mongo.Client, database string, collection string) *MongoConnection

func (*MongoConnection) C

func (ms *MongoConnection) C(collection string) *Collection

func (*MongoConnection) Close

func (ms *MongoConnection) Close(ctx context.Context) error

Close represents mongo session closing within the context deadline

func (*MongoConnection) DropDatabase

func (ms *MongoConnection) DropDatabase(ctx context.Context) error

func (*MongoConnection) GetConfiguredCollection

func (ms *MongoConnection) GetConfiguredCollection() *Collection

func (*MongoConnection) GetMongoCollection

func (ms *MongoConnection) GetMongoCollection() *mongo.Collection

func (*MongoConnection) ListCollectionsFor

func (ms *MongoConnection) ListCollectionsFor(ctx context.Context, database string) ([]string, error)

func (*MongoConnection) Ping

func (ms *MongoConnection) Ping(ctx context.Context, timeoutInSeconds time.Duration) error

type MongoConnectionConfig

type MongoConnectionConfig struct {
	IsSSL                   bool
	ConnectTimeoutInSeconds time.Duration
	QueryTimeoutInSeconds   time.Duration

	Username                      string
	Password                      string
	ClusterEndpoint               string
	Database                      string
	Collection                    string
	ReplicaSet                    string
	IsStrongReadConcernEnabled    bool
	IsWriteConcernMajorityEnabled bool
}

func (*MongoConnectionConfig) GetConnectionURI

func (m *MongoConnectionConfig) GetConnectionURI(isSSL bool) string

type MongoConnector

type MongoConnector interface {
	Ping(ctx context.Context) error
	C(collection string) *Collection
	Close(ctx context.Context) error
	GetCollectionsFor(ctx context.Context, database string) ([]string, error)
	GetConfiguredCollection() *Collection
	GetMongoCollection() *mongo.Collection
	DropDatabase(ctx context.Context) error
}

type MongoError

type MongoError struct {
	Reason string
	Inner  error
}

func (*MongoError) Error

func (m *MongoError) Error() string

func (*MongoError) Unwrap

func (m *MongoError) Unwrap() error

type Must

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

func (*Must) Remove

func (m *Must) Remove(ctx context.Context, selector interface{}) (*CollectionDeleteResult, error)

Remove deletes records based on the provided selector, must delete at least one record

func (*Must) RemoveId

func (m *Must) RemoveId(ctx context.Context, id interface{}) (*CollectionDeleteResult, error)

RemoveId deletes record based on the id selector must delete at least one record

func (*Must) Update

func (m *Must) Update(ctx context.Context, selector interface{}, update interface{}) (*CollectionUpdateResult, error)

Update modifies records located by a provided selector, must modifiy one record

func (*Must) UpdateId

func (m *Must) UpdateId(ctx context.Context, id interface{}, update interface{}) (*CollectionUpdateResult, error)

UpdateId modifies records located by a provided Id selector, must modifiy one record

type Timestamps

type Timestamps struct {
	LastUpdated     time.Time            `bson:"last_updated,omitempty"     json:"last_updated,omitempty"`
	UniqueTimestamp *primitive.Timestamp `bson:"unique_timestamp,omitempty" json:"-"`
}

Timestamps represent an object containing time stamps keep these in sync with above const

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL