mongodb

package
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Dec 30, 2022 License: MIT Imports: 22 Imported by: 1

Documentation

Index

Constants

View Source
const (
	SetOperation elementBuilderOperation = iota
	SetOnInsertOperation
	UnsetOperation
	FilterOperation
)
View Source
const (
	GreaterThan        filterOperation = "gt"
	GreaterOrEqualThan filterOperation = "ge"
	LowerThan          filterOperation = "lt"
	LowerOrEqualThan   filterOperation = "le"
	Equal              filterOperation = "eq"
	NotEqual           filterOperation = "ne"
	Contains           filterOperation = "contains"
	StartsWith         filterOperation = "startswith"
	EndsWith           filterOperation = "endswith"
	RegEx              filterOperation = "regex"
)
View Source
const (
	Asc  mongoSort = 1
	Desc mongoSort = -1
)
View Source
const (
	Custom pipelineType = iota
	AddFields
	Count
	Limit
	Lookup
	Match
	MatchField
	Page
	Project
	ProjectField
	Skip
	Sort
	SortField
	SortAfter
	SortAfterField
	Unwind
)

Variables

View Source
var ErrInvalidDestination = errors.New("destination must be a pointer type")

ErrInvalidDestination Invalid destination error

View Source
var ErrInvalidInput = errors.New("odata syntax error")

ErrInvalidInput OData syntax error definition

View Source
var ErrNoElements = errors.New("no elements to process")

Functions

func ApplyFilter

func ApplyFilter(node *parser.ParseNode) (bson.M, error)

func CreateUpdateModel

func CreateUpdateModel(value interface{})

Types

type BuilderOptions

type BuilderOptions int
const (
	UpsertBuildOption BuilderOptions = 1
)

type DeleteOneBuilder

type DeleteOneBuilder struct {
	LiteralFilter string
	Filters       []builderElement
}

func NewDeleteOneBuilder

func NewDeleteOneBuilder() *DeleteOneBuilder

func (*DeleteOneBuilder) Build

Build Builds the model to use during the query

func (*DeleteOneBuilder) Filter

func (c *DeleteOneBuilder) Filter(query string) *DeleteOneBuilder

Filter creates a filter for the model, this will allow to update just a subset of the collection if no filter is present it will apply the operation to all documents in the collection You can use odata type of query, for example:

builder.Filter("userId eq 'some_id'")

func (*DeleteOneBuilder) FilterBy

func (c *DeleteOneBuilder) FilterBy(key string, operation filterOperation, value interface{}) *DeleteOneBuilder

FilterBy creates a filter for the model using the field, operation and value to filter on if you have several filters applied they will always be joined by AND, no OR is permitted for example:

builder.FilterBy("userId", Equals, "some_id")

type FilterParser

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

func NewFilterParser

func NewFilterParser(filter string) *FilterParser

NewFilterParser Creates a nem Filter Parser from a odata type of query

func (*FilterParser) Parse

func (filterParser *FilterParser) Parse() (interface{}, error)

Parse Creates a MongoDB compatible filter from a odata type of query

type MongoClient

type MongoClient interface {
	Database(string) MongoDatabaseClient
	Connect() error
	StartSession() (mongoSession, error)
}

type MongoCollectionClient

type MongoCollectionClient interface {
	Find(context.Context, interface{}) (mongoCursor, error)
	FindOne(context.Context, interface{}) mongoSingleResult
	InsertOne(context.Context, interface{}) (interface{}, error)
}

type MongoDBService

type MongoDBService struct {
	ConnectionString   string
	GlobalDatabaseName string
	TenantDatabaseName string
}

MongoDBService structure

func Get

func Get() *MongoDBService

Get Gets the current global service returns a MongoDBService pointer

func Init

func Init() *MongoDBService

Init initiates the MongoDB service and global database factory returns a MongoDBService pointer

func New

func New() *MongoDBService

New Creates a MongoDB service using the default configuration This uses the environment variables to define the connection and the database name, the variables are: MONGODB_CONNECTION_STRING: for the connection string MONGODB_DATABASENAME: for the database name returns a MongoDBService pointer

func NewWithOptions

func NewWithOptions(options MongoDBServiceOptions) *MongoDBService

NewWithOptions Creates a MongoDB service passing the options object returns a MongoDBService pointer

func (*MongoDBService) GetTenant

func (service *MongoDBService) GetTenant() string

func (*MongoDBService) GlobalDatabase

func (service *MongoDBService) GlobalDatabase() *MongoFactory

GlobalDatabase Gets the global database factory and initiate it ready for consuption. This will try to only keep a client per session to avoid starvation of the clients returns a MongoFactory pointer

func (*MongoDBService) TenantDatabase

func (service *MongoDBService) TenantDatabase() *MongoFactory

TenantDatabase Gets the tenant database factory and initiate it ready for consumption if there is no tenant set this will bring the global database and we will treat it as a single tenant system. This will try to only keep a client per session to avoid starvation of the clients returns a MongoFactory pointer

func (*MongoDBService) WithDatabase

func (service *MongoDBService) WithDatabase(databaseName string) *MongoDBService

WithDatabase Sets the global database name returns a MongoDBService pointer

type MongoDBServiceOptions

type MongoDBServiceOptions struct {
	ConnectionString   string
	GlobalDatabaseName string
}

MongoDBServiceOptions structure

type MongoDatabaseClient

type MongoDatabaseClient interface {
	Collection(name string)
}

type MongoDatabaseContext

type MongoDatabaseContext struct {
	CurrentDatabaseName string
	ConnectionString    string
	CurrentCollection   string
}

type MongoDefaultRepository

type MongoDefaultRepository struct {
	Database   *mongoDatabase
	Collection *mongoCollection
	// contains filtered or unexported fields
}

func (*MongoDefaultRepository) DeleteMany

func (r *MongoDefaultRepository) DeleteMany(filter interface{}) (*mongoDeleteResult, error)

DeleteMany Deletes documents in a collection based on a filter, the filter can be a valid bson document or you can use a odata type query.

Example:

repository.DeleteMany(bson.M{"userId": "someId"})

or

repository.DeleteMany("userId eq 'someId'")

func (*MongoDefaultRepository) DeleteOne

func (r *MongoDefaultRepository) DeleteOne(model *MongoDeleteOneModel) (*mongoDeleteResult, error)

DeleteOne Deletes a document in a collection using a DeleteOneModel, this can be constructed using strong typed language using the DeleteOneModelBuilder

func (*MongoDefaultRepository) Find

func (repository *MongoDefaultRepository) Find(filter interface{}) (*mongoCursor, error)

Find finds records with a filter and returns a cursor to iterate trough them

Example:

repository.Find(bson.M{"userId", "someId"})

You can also use a string query similar to odata

for example

repository.Find("userId eq 'someId'")

or a function like startswith

repository.Find("startswith(userId, 'someId'")

func (*MongoDefaultRepository) FindBy

func (r *MongoDefaultRepository) FindBy(filter string) (*mongoCursor, error)

Find finds records with a filter and returns a cursor to iterate trough them You can also use a string query similar to odata, for example

repository.Find("userId eq 'someId'")

or a function like startswith

repository.Find("startswith(userId, 'someId'")

func (*MongoDefaultRepository) FindFieldBy

func (r *MongoDefaultRepository) FindFieldBy(fieldName string, operation filterOperation, value interface{}) (*mongoCursor, error)

FindFieldBy finds a record using a specific field and operation, this is a more restricted filtering but helps with the strong typed query that can be produced

Example:

repository.FindFieldBy("userId" , mongo.Equal, "someId")

func (*MongoDefaultRepository) FindOne

func (r *MongoDefaultRepository) FindOne(filter interface{}) *mongoSingleResult

FindOne Finds a single result based on a filter, this can be a bson document or a odata type of query.

Example:

repository.FindOne("userId eq 'someId'")

or

repository.FindOne(bson.M{"userId": "someId"})

The result will be a `mongoSingleResult` that can be decoded to any interface

func (*MongoDefaultRepository) InsertMany

func (r *MongoDefaultRepository) InsertMany(elements ...interface{}) (*mongoInsertManyResult, error)

InsertMany Inserts multiple records in the collection and returns the inserted id's

func (*MongoDefaultRepository) InsertOne

func (r *MongoDefaultRepository) InsertOne(element interface{}) (*mongoInsertOneResult, error)

InsertOne Inserts a record int the collection and returns the inserted id

func (*MongoDefaultRepository) OData

func (repository *MongoDefaultRepository) OData() *ODataParser

OData Creates an OData parser to return data

func (*MongoDefaultRepository) Pipeline

func (repository *MongoDefaultRepository) Pipeline() *PipelineBuilder

Pipeline Creates an empty pipeline for querying mongodb

func (*MongoDefaultRepository) UpdateMany

func (r *MongoDefaultRepository) UpdateMany(models ...*MongoUpdateOneModel) (*mongoBulkWriteResult, error)

UpdateMany updates documents in the collection using a UpdateOneModel, this can be constructed using strong typed language when called the UpdateOneModelBuilder.

func (*MongoDefaultRepository) UpdateOne

func (r *MongoDefaultRepository) UpdateOne(model *MongoUpdateOneModel) (*mongoUpdateResult, error)

UpdateOne updates a document in a collection using a UpdateOneModel, this can be constructed using strong typed language when called the UpdateOneModelBuilder It will return the number of affected documents

func (*MongoDefaultRepository) UpsertMany

func (r *MongoDefaultRepository) UpsertMany(models ...*MongoUpdateOneModel) (*mongoBulkWriteResult, error)

UpsertMany Similar to UpdateMany this updates or inserts (if it does not exists) a document in a collection using a UpdateOneModel, this can be constructed using strong typed language when called the UpdateOneModelBuilder.

func (*MongoDefaultRepository) UpsertOne

func (r *MongoDefaultRepository) UpsertOne(model *MongoUpdateOneModel) (*mongoUpdateResult, error)

UpsertOne similar to the UpdateOne this updates or inserts (if it does not exists) a document in a collection using a UpdateOneModel, this can be constructed using strong typed language when called the UpdateOneModelBuilder. It will return the number of affected documents

type MongoDeleteOneModel

type MongoDeleteOneModel struct {
	Filter interface{}
	Hint   interface{}
	// contains filtered or unexported fields
}

func (MongoDeleteOneModel) String

func (model MongoDeleteOneModel) String() string

Transforms the model into a json string representation

type MongoFactory

type MongoFactory struct {
	Context         *execution_context.Context
	Client          *mongoClient
	Database        *mongoDatabase
	DatabaseContext *MongoDatabaseContext
	Logger          *log.Logger
}

MongoFactory MongoFactory Entity

func NewFactory

func NewFactory(connectionString string) *MongoFactory

NewFactory Creates a brand new factory for a specific connection string this will create and attach a mongo client that it will use for all connections returns a pointer to a MongoFactory object

func (*MongoFactory) GetClient

func (f *MongoFactory) GetClient() *mongoClient

GetClient This will either return an already initiated client or the current active client in the factory, this will avoid having unclosed clients if you need a brand new client please use the NewFactory method to create a brand new factory. returns a mongoClient object

func (*MongoFactory) GetCollection

func (f *MongoFactory) GetCollection(collectionName string) *mongoCollection

GetCollection Get a collection from the current database returns a mongoCollection object

func (*MongoFactory) GetDatabase

func (f *MongoFactory) GetDatabase(databaseName string) *mongoDatabase

GetDatabase Get a database from the current cluster and sets it in the database context returns a mongoDatabase object

func (*MongoFactory) NewDatabaseRepository

func (mongoFactory *MongoFactory) NewDatabaseRepository(database string, collection string) MongoRepository

NewDatabaseRepository Creates a new repository for a specific collection in a database, this will allow you to perform queries and aggregations in the collection Returns an implemented interface MongoRepository

func (*MongoFactory) NewRepository

func (mongoFactory *MongoFactory) NewRepository(collection string) MongoRepository

NewRepository Creates a new repository for a specific collection, this will allow you to perform queries and aggregations in the collection Returns an implemented interface MongoRepository

func (*MongoFactory) StartSession

func (f *MongoFactory) StartSession() (mongo.Session, error)

StartSession Starts a session in the mongodb client

func (*MongoFactory) WithDatabase

func (f *MongoFactory) WithDatabase(databaseName string) *MongoFactory

type MongoRepository

type MongoRepository interface {
	OData() *ODataParser
	Pipeline() *PipelineBuilder
	Find(filter interface{}) (*mongoCursor, error)
	FindBy(filter string) (*mongoCursor, error)
	FindFieldBy(fieldName string, operation filterOperation, value interface{}) (*mongoCursor, error)
	FindOne(filter interface{}) *mongoSingleResult
	InsertOne(element interface{}) (*mongoInsertOneResult, error)
	InsertMany(elements ...interface{}) (*mongoInsertManyResult, error)
	UpdateOne(model *MongoUpdateOneModel) (*mongoUpdateResult, error)
	UpdateMany(models ...*MongoUpdateOneModel) (*mongoBulkWriteResult, error)
	UpsertOne(model *MongoUpdateOneModel) (*mongoUpdateResult, error)
	UpsertMany(models ...*MongoUpdateOneModel) (*mongoBulkWriteResult, error)
	DeleteOne(model *MongoDeleteOneModel) (*mongoDeleteResult, error)
	DeleteMany(filter interface{}) (*mongoDeleteResult, error)
}

type MongoUpdateOneModel

type MongoUpdateOneModel struct {
	Filter interface{}
	Hint   interface{}
	Update interface{}
	// contains filtered or unexported fields
}

func (MongoUpdateOneModel) String

func (model MongoUpdateOneModel) String() string

Transforms the model into a json string representation

type ODataParser

type ODataParser struct {
	Collection *mongoCollection
}

ODataParser Structure element

func EmptyODataParser

func EmptyODataParser(collection *mongoCollection) *ODataParser

EmptyODataParser Creates an empty odata parser for a specific collection

func (*ODataParser) Decode

func (odataParser *ODataParser) Decode(query url.Values, destination interface{}) error

Decode Decodes a odata query url to a destination object, this needs to be a pointer This will return the object but not an odata response returns error if there was an error in the query

func (*ODataParser) GetODataResponse

func (odataParser *ODataParser) GetODataResponse(query url.Values) (*models.ODataResponse, error)

TODO: Implement inner count GetODataResponse Creates a odata response from an odata url query including count

func (*ODataParser) Query

func (odataParser *ODataParser) Query(query url.Values) (*mongoCursor, error)

Query creates a mongo query based on odata parameters returns a cursor ready to be iterated or an error if something goes wrong

type Pipeline

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

type PipelineBuilder

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

func NewEmptyPipeline

func NewEmptyPipeline(collection *mongoCollection) *PipelineBuilder

NewEmptyPipeline Creates a new pipeline builder for a specific collection

func (*PipelineBuilder) Add

func (pipelineBuilder *PipelineBuilder) Add(pipeline bson.D) *PipelineBuilder

Add Adds a user custom pipeline to the builder, this can be any valid mongo pipeline

func (*PipelineBuilder) AddField

func (pipelineBuilder *PipelineBuilder) AddField(field string, value interface{}) *PipelineBuilder

AddField Adds a field to the result

func (*PipelineBuilder) Aggregate

func (pipelineBuilder *PipelineBuilder) Aggregate() (*mongoCursor, error)

func (*PipelineBuilder) Count

func (pipelineBuilder *PipelineBuilder) Count() *PipelineBuilder

Count Adds a count pipeline, this will overseed any other pipeline and will always return a count pipeline response with a value

func (*PipelineBuilder) CountCollection

func (pipelineBuilder *PipelineBuilder) CountCollection() int

CountCollection This will count the pipeline collection excluding anything from the pipelines we can use this for odata responses or to count how many objects the collection has

func (*PipelineBuilder) CountPipeline

func (pipelineBuilder *PipelineBuilder) CountPipeline() int

CountPipeline Gets the pipeline count based in the current set of pipelines, this will take into consideration any filtering done by the user but not any system pipelines

func (*PipelineBuilder) Filter

func (pipelineBuilder *PipelineBuilder) Filter(filter string) *PipelineBuilder

Filter Adds a Match pipeline using a odata type of query for a easier and powerful query language If the expressing fails to parse it will not be added to the pipeline

func (*PipelineBuilder) FilterBy

func (pipelineBuilder *PipelineBuilder) FilterBy(field string, operation filterOperation, value interface{}) *PipelineBuilder

FilterBy Adds a Match pipeline for a specific field, this allow simple operations always with and joining fields if they are more than one, use the Filter pipeline to pass in a more complex odata type of query for a better control of the filtering

func (*PipelineBuilder) FilterByUserPipelines

func (pipelineBuilder *PipelineBuilder) FilterByUserPipelines() *PipelineBuilder

FilterByUserPipelines Sets the pipeline filter to only execute the pipelines created by the user, this allows the execution to skip any internal ones like MATCH or Project

func (*PipelineBuilder) Limit

func (pipelineBuilder *PipelineBuilder) Limit(limit int) *PipelineBuilder

Limit Adds a limit pipeline, if the limit is lower or equal than 0 then tno pipeline is added

func (*PipelineBuilder) Lookup

func (pipelineBuilder *PipelineBuilder) Lookup(from string, localField string, foreignField string, fieldAs string) *PipelineBuilder

Lookup Adds a lookup pipeline to join other collections into this one as subobjects

func (*PipelineBuilder) Match

func (pipelineBuilder *PipelineBuilder) Match(value interface{}) *PipelineBuilder

Match Adds a Match pipeline using a complex interface, this allows finer tunning in the required query, there is no validation of the passed value and it needs to be a valid query. Use the filter pipeline if you want to pass an odata type of query

func (*PipelineBuilder) Page

func (pipelineBuilder *PipelineBuilder) Page(page int, pageSize int) *PipelineBuilder

Page Creates a paging pipeline based in the page number and page size, this will generate a $skip and a $limit pipeline if the page and skip are filled in

func (*PipelineBuilder) Project

func (pipelineBuilder *PipelineBuilder) Project(fields interface{}) *PipelineBuilder

Project Adds a projection pipeline using a complex interface, this allows finer tunning in the required query, there is no validation of the passed value and it needs to be a valid query. Use ProjectField to build it using individual fields

func (*PipelineBuilder) ProjectField

func (pipelineBuilder *PipelineBuilder) ProjectField(field string) *PipelineBuilder

ProjectField adds a field to be projected by the pipeline, this allows to easily build a projection of complex fields without adding a pre built interface.

func (*PipelineBuilder) ProjectFieldAs

func (pipelineBuilder *PipelineBuilder) ProjectFieldAs(field string, projectedAs string) *PipelineBuilder

ProjectFieldAs adds a field to be projected by the pipeline and assign a different property name, this allows to easily build a projection of complex fields without adding a pre built interface.

func (*PipelineBuilder) Skip

func (pipelineBuilder *PipelineBuilder) Skip(skip int) *PipelineBuilder

Skip adds a skip pipeline, if the skip is lower than 0 then no pipeline is added

func (*PipelineBuilder) Sort

func (pipelineBuilder *PipelineBuilder) Sort(fields interface{}) *PipelineBuilder

Adds a sort pipeline, this allows fields to be sorted, be wary of the order sort is placed during the pipeline construction, this might impact the results

func (*PipelineBuilder) SortAtEnd

func (pipelineBuilder *PipelineBuilder) SortAtEnd(fields interface{}) *PipelineBuilder

SortAtEnd Adds a sort pipeline that runs at the very end of each pipeline, this is commonly used for example during odata process where we might have a inner sorting but we want to sort it based on that query

func (*PipelineBuilder) SortBy

func (pipelineBuilder *PipelineBuilder) SortBy(field string, order mongoSort) *PipelineBuilder

SortBy Adds a Sort pipeline using fields to sort, the order of the fields will be kept when building the pipeline and any repeating field will only update the order

func (*PipelineBuilder) SortByAtEnd

func (pipelineBuilder *PipelineBuilder) SortByAtEnd(field string, order mongoSort) *PipelineBuilder

SortBy SortAtEnd Adds a sort pipeline that runs at the very end of each pipeline, this is commonly used for example during odata process where we might have a inner sorting but we want to sort it based on that query using fields to sort, the order of the fields will be kept when building the pipeline and any repeating field will only update the order

func (*PipelineBuilder) Unwind

func (pipelineBuilder *PipelineBuilder) Unwind(path string) *PipelineBuilder

Unwind Adds an Unwind pipeline to flatten an array

func (*PipelineBuilder) UnwindWidthIndex

func (pipelineBuilder *PipelineBuilder) UnwindWidthIndex(path string, includeArrayIndex string, preserveNullAndEmptyArrays bool) *PipelineBuilder

UnwindWidthIndex Adds an Unwind pipeline to flatten an array and includes the index in the object

func (*PipelineBuilder) WithOptions

func (pipelineBuilder *PipelineBuilder) WithOptions(options PipelineOptions) *PipelineBuilder

WithOptions Sets the pipeline aggregation options, this allows for a more granular execution of some of the internal pipelines, for example execute a count with only the users assigned pipelines and none of the other ones

type PipelineOptions

type PipelineOptions struct {
	IncludeAddFields  bool
	IncludeCount      bool
	IncludeLimit      bool
	IncludeMatch      bool
	IncludeProjection bool
	IncludeSkip       bool
	IncludeSort       bool
	IncludeUser       bool
	IncludeUnwind     bool
}

type UpdateOneModelBuilder

type UpdateOneModelBuilder struct {
	LiteralFilter string
	Elements      []builderElement
}

func NewUpdateOneModelBuilder

func NewUpdateOneModelBuilder() *UpdateOneModelBuilder

NewUpdateOneModelBuilder Creates a new builder for an updateone model

func (*UpdateOneModelBuilder) Build

Build Builds the model to use during the query you can pass options for the build process, for example

builder.Build(UpsertBuildOption)

func (*UpdateOneModelBuilder) Encode

func (c *UpdateOneModelBuilder) Encode(element interface{}, ignoredFields ...string) *UpdateOneModelBuilder

Encode creates a bson representation of an already existing interface, this is helpful to pass an object and let the encode generate the sets for all properties. you can also ignore fields if you have used any of the Set or SetOnInsert methods to build this model, they superseed the encode for example:

var obj := struct {
	Name string
	Timestamp time.Time
}{
	Name: "SomeProperty"
	Timestamp: time.
}
builder.Encode(obj, "Timestamp")

func (*UpdateOneModelBuilder) Filter

Filter creates a filter for the model, this will allow to update just a subset of the collection if no filter is present it will apply the operation to all documents in the collection You can use odata type of query, for example:

builder.Filter("userId eq 'some_id'")

func (*UpdateOneModelBuilder) FilterBy

func (c *UpdateOneModelBuilder) FilterBy(key string, operation filterOperation, value interface{}) *UpdateOneModelBuilder

FilterBy creates a filter for the model using the field, operation and value to filter on if you have several filters applied they will always be joined by AND, no OR is permitted for example:

builder.FilterBy("userId", Equals, "some_id")

func (*UpdateOneModelBuilder) Set

func (c *UpdateOneModelBuilder) Set(field string, value interface{}) *UpdateOneModelBuilder

Set Sets a field to be updated, this will add the property if it does not exist in the model

func (*UpdateOneModelBuilder) SetOnInsert

func (c *UpdateOneModelBuilder) SetOnInsert(field string, value interface{}) *UpdateOneModelBuilder

SetOnInsert, only updates a value on insert, if the operation is a update it will be ignored

func (*UpdateOneModelBuilder) Unset

Unset Unsets a field in the document, this will effectively remove the property from the document

Jump to

Keyboard shortcuts

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