easymongo

package module
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2020 License: MIT Imports: 12 Imported by: 1

README

0.x project - not ready for the light of day

Coming soon to an IDE near you... Build Status Coverage Status

Easy Mongo

This project aims to be a friendly (somewhat opinionated) abstraction on top of mongo-go-driver. The official driver provides much more fine-grained control than this project attempts to solve.

TODO: C.R.U.D. Examples

Create/Read/Update/Destroy!

Get Data into the Database

Let's talk about first how to get data into the database.

Find it and query it back
Modify it
Delete it
Examples
easymongo.CreateCreds()
conn := easymongo.Connect("mongo://127.0.0.1")
type myObj struct {}
foo := myObj{}
// TODO: Update this to the new syntax
err = conn.GetDatabase("my_db").GetCollection("my_coll").Insert(&foo)
Why use easymongo?

You should use easymongo if:

  • You are planning on connecting primarily to a single cluster or instance
  • Are looking to make common query operations with fewer lines of code
  • Are okay with some logic being extrapolated and defaults assumed
  • Accept one developer's opinionated approach to mongo in golang ;-)

The mongo-go-driver was written with the mindset of allowing complete control of every part of the query process. This project aims to build on that power to make life simple.

This can be run alongside mongo-go-driver in the same project without fear of conflicts. In fact, you can call easymongo.ConnectUsingMongoClient(client *mongo.Client) if you already have a pre-initialized mongo.Client. You will be able to start consuming the easymongo.Connection methods immediately.

How are things different from mongo-go-driver?

Some functionality (such as the ability to directly set the context on a query) has been abstracted, while other functionality has intentionally been ignored in order to keep it simple for the core use cases.

This project is built on top of mongo-go-driver, so if you desire additional power (and really, who doesn't?), you can call MongoDriverClient() on the Connection object to obtain direct access to the *mongo.Client object. From there, the world is your oyster.

The decision (which I expect to see at least 1 GitHub issue debating) was made to cache the most recent mongo connection in a global variable under the covers in easymongo. This enables the following ease-of-use functions that would otherwise not be available:

Contributors

Anyone is welcome to submit PRs. Please ensure there is test coverage before submitting the request.

TODO

  • Support new tag - jbson - which is a common tag that can be used for both json and bson
  • Support find
  • Support update/upsert/replace
  • Support count
  • Support delete
  • Support insert
  • Support gridfs
  • Support watching
  • Support collection ease-of-use enhancements
  • Support indices ease-of-use enhancements
  • Prevent users from being able to reconnect over and over to cluster - cache connection
  • Add helpers for letting users run tests that:
    • automatically spin up a docker container if a DB isn't available locally
    • allow mocking of commands
    • support exporting data from the DB
    • support easy preloading of exported data
  • Make running general mongo commands easier
  • Add a tool for converting mongo queries to golang mongo queries
  • Support optionally returning ErrNotFound using a global option when no update/upsert/delete results are found.
  • Handle nil slice/map auto-initialization / type
  • Handle datetime objects being strings
  • Add DistinctStrings(), DistinctInts(), Distinct()
  • Document bson.M vs bson.D
  • Add the option to create easymongo from an existing mongo-go-driver session
  • Support read/write concern
  • Add option for ErrNotFound
  • Create docs on using bson tags
  • Link to mongo-go-driver docs where appropriate
  • Change Do() to Execute()

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNotImplemented is raised when a function is not yet supported/complete
	// This is mostly used to help track development progress
	ErrNotImplemented = errors.New("this feature has not yet been implemented")
	// ErrTimeoutOccurred denotes a query exceeded the max call time it was allowed
	ErrTimeoutOccurred = NewMongoErr(errors.New("timeout during database transaction"))
	// ErrPointerRequired denotes that the provided result object is being passed by value rather than reference
	ErrPointerRequired = NewMongoErr(errors.New("a pointer is required in order to unpack the resultant value from a query"))
)

Functions

This section is empty.

Types

type Aggregation

type Aggregation struct{}

func (*Aggregation) All

func (p *Aggregation) All(result interface{}) error

TODO: Aggregation.All

func (*Aggregation) AllowDiskUse

func (p *Aggregation) AllowDiskUse() *Aggregation

TODO: Aggregation.AllowDiskUse

func (*Aggregation) Batch

func (p *Aggregation) Batch(n int) *Aggregation

TODO: Aggregation.Batch

func (*Aggregation) Explain

func (p *Aggregation) Explain(result interface{}) error

TODO: Aggregation.Explain

func (*Aggregation) Iter

func (p *Aggregation) Iter() *Iter

TODO: Aggregation.Iter

func (*Aggregation) One

func (p *Aggregation) One(result interface{}) error

TODO: Aggregation.One

type Collection

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

Collection is a helper for accessing and modifying mongo collections

func GetCollection

func GetCollection(dbName, collectionName string) *Collection

GetCollection is a shorthand for getting a collection by name using the globally initialized database. Consider using db.Collection() if you wish to explicitly consume a given connection pool.

func (*Collection) Connection

func (c *Collection) Connection() *Connection

Connection returns the connection associated with this collection.

func (*Collection) Count

func (c *Collection) Count() (int, error)

Count returns the count of the number of documents in the collection. TODO: Should we be using estimatedCount here instead?

func (*Collection) DefaultCtx

func (c *Collection) DefaultCtx() (context.Context, context.CancelFunc)

DefaultCtx returns the appropriate context using the default timeout specified at conneciton time.

func (*Collection) DeleteByID

func (c *Collection) DeleteByID(id interface{})

func (*Collection) DeleteMany

func (c *Collection) DeleteMany()

func (*Collection) DeleteOne

func (c *Collection) DeleteOne()

func (*Collection) Drop added in v0.0.6

func (c *Collection) Drop() (err error)

Drop drops the collection this object is referring to.

func (*Collection) Find

func (c *Collection) Find(filter interface{}) (q *FindQuery)

Find allows a user to execute a standard find() query. findOne(), find() and findAnd*() is run when a user calls:

q.One(), q.Many(). q.FindAnd().Replace(), q.FindAnd().Update() and q.FindAnd().Delete()

TODO: Consider using bsoncore.Doc rather than interface?

func (*Collection) FindByDate

func (c *Collection) FindByDate(after *time.Time, before *time.Time, additionalFilters bson.M) *FindQuery

FindByDate is a helper for filtering documents by times using the ObjectID. This is typically helpful when dealing with large collections as Skip and Limit will become less performant.

func (*Collection) FindByID

func (c *Collection) FindByID(id interface{}, result interface{}) (err error)

FindByID wraps Find, ultimately executing `findOne("_id": providedID)` Typically, the provided id is a pointer to a *primitive.ObjectID.

func (*Collection) GetDatabase

func (c *Collection) GetDatabase() *Database

GetDatabase returns the database associated with the database/collection.

func (*Collection) Insert

func (c *Collection) Insert() *InsertQuery

Insert constructs and returns an InsertQuery object. Now run .One() or .Many() using this handle.

func (*Collection) MongoDriverCollection added in v0.0.6

func (c *Collection) MongoDriverCollection() *mongo.Collection

MongoDriverCollection returns the native mongo driver collection object (should you wish to interact with it directly)

func (*Collection) Query

func (c *Collection) Query(filter interface{}) *Query

Query returns an initialized query object from a collection

func (*Collection) Replace

func (c *Collection) Replace(filter interface{}, obj interface{}) *ReplaceQuery

Replace returns a ReplaceQuery. Trying running `.One()` against this. This is used to replace an entire object. If you are looking to update just part of a document (e.g. $set a field, $inc a counter up or down, etc.) you should instead use Update().One().

func (*Collection) ReplaceByID

func (c *Collection) ReplaceByID(id interface{}, obj interface{}) (err error)

ReplaceByID is a friendly helper that wraps Replace(bson.M{"_id": id}, obj).Execute()

func (*Collection) Update added in v0.0.6

func (c *Collection) Update(filter interface{}, update interface{}) *UpdateQuery

Update todo: update docs

func (*Collection) UpdateByID

func (c *Collection) UpdateByID(id interface{}, update interface{}) (err error)

UpdateByID wraps UpdateOne to update a single record by ID (should the record exist).

func (*Collection) Upsert added in v0.0.6

func (c *Collection) Upsert(filter interface{}, updateQuery interface{}) *UpdateQuery

Upsert updates the first matching document using the upsert option once .One() has been called. If no option overrides are necessary, consider using UpsertOne or UpsertByID.

func (*Collection) UpsertByID

func (c *Collection) UpsertByID(id interface{}, updateQuery interface{}) (err error)

UpsertByID performs an upsert style update using the updateQuery against the provided _id.

func (*Collection) UpsertMany

func (c *Collection) UpsertMany(filter interface{}, updateQuery interface{}) (matchedCount, updatedCount int, err error)

UpsertMany performs an update style upsert using updateMany(). Should no documents match the query, then a new document is created. updateQuery is typically of some sort of $set or $push bson.M.

func (*Collection) UpsertOne

func (c *Collection) UpsertOne(filter interface{}, updateQuery interface{}) error

UpsertOne updates the first matching document using the default upsert options. This call is equivalent to c.Upsert(filter, updateQuery).One()

type Connection

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

Connection represents a connection to the mongo cluster/instance.

func Connect

func Connect(mongoURI string) *Connection

Connect connects to the given mongo URI. Connect wraps ConnectWithOptions. If you are using just a mongoUri for connection, this should be all you need. However, if you need to configure additional options, it is recommened to instead use ConnectWithOptions. If a connection does not suceed when using Connect, then a panic occurs.

func ConnectUsingMongoClient

func ConnectUsingMongoClient(client *mongo.Client, mongoURI string) *Connection

ConnectUsingMongoClient accepts an initialized mongo.Client and returns an easymongo Connection This is useful if you want the power of standing up your own mongo.Client connection. mongoURI is used for informational purposes - feel free to ignore it if you don't need it.

func ConnectWithOptions

func ConnectWithOptions(mongoURI string, mongoOpts *MongoConnectOptions) (*Connection, error)

ConnectWithOptions connects to the specified mongo URI. A note that calling this function has the side-effect of setting the global cached connection to this value. If you are not using the global connection value and instead using the value explicitly returned from this function, then no need to worry about this. If a connection does not succeed, then an error is returned. TODO: Configure and consume mongoOpts

func GetCurrentConnection

func GetCurrentConnection() *Connection

GetCurrentConnection returns the current connection cached in the global context.

func (*Connection) Database added in v0.0.6

func (conn *Connection) Database(dbName string) *Database

Database returns the database object associated with the provided database name

func (*Connection) DatabaseNames

func (conn *Connection) DatabaseNames() []string

DatabaseNames returns a list of the databases available in the connected cluster as a list of strings. If an error occurrent, an empty list is returned.

func (*Connection) GetDefaultTimeoutCtx

func (conn *Connection) GetDefaultTimeoutCtx() (ctx context.Context, cancelFunc context.CancelFunc)

GetDefaultTimeoutCtx returns a context based on if a default timeout has been set. If no timeout was specified, then context.Background() is returned.

func (*Connection) ListDatabases

func (conn *Connection) ListDatabases() (dbList []*Database)

ListDatabases returns a list of databases available in the connected cluster as objects that can be interacted with.

func (*Connection) MongoDriverClient

func (conn *Connection) MongoDriverClient() *mongo.Client

MongoDriverClient returns the mongo.Client from mongo-go-driver - to allow for direct interaction with the mongo driver for those users searching for more fine-grained control.

func (*Connection) MongoURI

func (conn *Connection) MongoURI() string

MongoURI returns the URI of the mongo instance the test connection is tethered to.

func (*Connection) Ping

func (conn *Connection) Ping() (err error)

Ping attempts to ping the mongo instance

type Database

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

Database is helper for representing a database in a cluster.

func GetDatabase

func GetDatabase(dbName string) *Database

GetDatabase returns a database object for the named database using the most recently connected to mongo instance/cluster.

func (*Database) C

func (db *Database) C(name string) *Collection

C returns a Collection object that can be used to run queries on and create/drop indices C wraps Collection() for users who want to use short-hand to do queries. It is interchangeable with a call to db.Collection().

func (*Database) Collection

func (db *Database) Collection(name string) *Collection

Collection returns a Collection object that can be used to run queries on and create/drop indices It is interchangeable with C().

func (*Database) CollectionNames

func (db *Database) CollectionNames() (collectionNames []string, err error)

CollectionNames returns the names of the collections as strings.

func (*Database) DefaultCtx

func (db *Database) DefaultCtx() (context.Context, context.CancelFunc)

DefaultCtx returns the appropriate context using the default timeout specified at conneciton time.

func (*Database) Drop

func (db *Database) Drop() error

Drop drops a database from a mongo instance. Use with caution.

func (*Database) ListCollections

func (db *Database) ListCollections() ([]*Collection, error)

ListCollections returns a list of Collection objects that can be actioned against.

func (*Database) Name

func (db *Database) Name() string

Name returns the name of the database

type ExplainResult

type ExplainResult struct {
	QueryPlanner QueryPlanner `json:"queryPlanner"`
}

ExplainResult represents the results from a query documented here - https://docs.mongodb.com/manual/reference/command/explain/#dbcmd.explain TODO: Test that this actually unpacks and support the other two types of explain results.

type FindAndQuery

type FindAndQuery struct {
	*Query
	// contains filtered or unexported fields
}

FindAndQuery is used for Find().OneAnd() operations (e.g. Find().OneAnd().Replace())

func (*FindAndQuery) ArrayFilters added in v0.0.8

func (q *FindAndQuery) ArrayFilters(o *options.ArrayFilters) *FindAndQuery

ArrayFilters is used to hold filters for the array filters CRUD option. If a registry is nil, bson.DefaultRegistry will be used when converting the filter interfaces to BSON. TODO: ArrayFilters helpers

func (*FindAndQuery) BypassDocumentValidation added in v0.0.8

func (q *FindAndQuery) BypassDocumentValidation() *FindAndQuery

TODO: BypassDocumentValidation options docs

func (*FindAndQuery) Delete

func (q *FindAndQuery) Delete() (err error)

Delete ultimately ends up running `findOneAndDelete()`. If you do not need the existing value/object, it is recommended to instead run `collection.Delete().Execute()`

func (*FindAndQuery) Projection added in v0.0.8

func (q *FindAndQuery) Projection(projectionQuery interface{}) *FindAndQuery

Projection limits the information returned from the query. Whitelist fields using: `bson.M{"showThisField": 1}` Blacklist fields using: `bson.M{"someBigStructToHide": 0}`

func (*FindAndQuery) Replace

func (q *FindAndQuery) Replace(replacementObject interface{}) (err error)

Replace ultimately ends up running `findOneAndReplace()`. If you do not need the existing value/object, it is recommended to instead run `collection.Replace().Execute()`

func (*FindAndQuery) Update

func (q *FindAndQuery) Update(updateQuery interface{}) (err error)

Update ends up running `findAndModify()` - if you do not need the result object, consider running `collection.UpdateOne()` instead.

func (*FindAndQuery) Upsert added in v0.0.8

func (q *FindAndQuery) Upsert() *FindAndQuery

Upsert specifies that if a document doesn't exist that matches the update filter, then a new document will be created as a result of this query run.

type FindQuery

type FindQuery struct {
	*Query
	// contains filtered or unexported fields
}

FindQuery is a helper for finding and counting documents

func (*FindQuery) AllowDiskUse

func (q *FindQuery) AllowDiskUse() *FindQuery

AllowDiskUse sets a flag which allows queries to page to disk space should they exhaust their allotted memory.

func (*FindQuery) AllowPartialResults

func (q *FindQuery) AllowPartialResults() *FindQuery

AllowPartialResults allows an operation on a sharded cluster to return partial results (in the case that a shard is inaccessible). An error will not be returned should only partial results be returned.

func (*FindQuery) BatchSize

func (q *FindQuery) BatchSize(batchSize int) *FindQuery

BatchSize sets the max batch size returned by the server each time the cursor executes. Mostly useful when using Iter directly.

func (*FindQuery) Count

func (q *FindQuery) Count() (int, error)

Count counts the number of documents using the specified query

func (*FindQuery) Iter

func (q *FindQuery) Iter() (iter *Iter, err error)

Iter returns an iterator that can be used to walk over and unpack the results one at a time.

func (*FindQuery) Limit

func (q *FindQuery) Limit(limit int) *FindQuery

Limit sets the max value of responses to return when executing the query. A note that when working with larger datasets, it is much more performance to compare using collection.FindByDate

func (*FindQuery) Many

func (q *FindQuery) Many(results interface{}) error

Many executes the specified query using find() and unmarshals the result into the provided interface. Ensure interface{} is either a slice or a pointer to a slice.

func (*FindQuery) One

func (q *FindQuery) One(result interface{}) (err error)

One consumes the specified query and marshals the result into the provided interface.

func (*FindQuery) OneAnd

func (q *FindQuery) OneAnd(result interface{}) *FindAndQuery

OneAnd consumes the specified query and marshals the result into the provided interface once .Replace() or .Update() are called.

func (*FindQuery) Projection

func (q *FindQuery) Projection(projectionQuery interface{}) *FindQuery

Projection limits the information returned from the query. Whitelist fields using: `bson.M{"showThisField": 1}` Blacklist fields using: `bson.M{"someBigStructToHide": 0}`

func (*FindQuery) Skip

func (q *FindQuery) Skip(skip int) *FindQuery

Skip sets the skip value to bypass the given number of entries A note that when working with larger datasets, it is much more performance to compare using collection.FindByDate

type Index

type Index struct{}

type InputStage

type InputStage struct {
	Stage       string        `json:"stage"`
	InputStages []interface{} `json:"inputStages"`
}

type InsertQuery

type InsertQuery struct {
	Query
}

InsertQuery is a helper for constructing insertion operations

func (*InsertQuery) Many

func (iq *InsertQuery) Many(objsToInsert interface{}) (ids []*primitive.ObjectID, err error)

Many inserts a slice into a mongo collection. The ids of the inserted objects are returned. If an ID was not available (e.g. it was unset), an empty entry in the slice is returned. TODO: What should be the default behavior when an ID isn't returned? Note: Many() uses reflect to coerce an interface to an interface slice. This results in a minor O(N) performance hit. If inserting large quanities of items and every nanosecond counts, cast your slice to a slice interface yourself (which is an O(1) operation), and call ManyFromInterfaceSlice().

func (*InsertQuery) ManyFromInterfaceSlice

func (iq *InsertQuery) ManyFromInterfaceSlice(objsToInsert []interface{}) (ids []*primitive.ObjectID, err error)

ManyFromInterfaceSlice inserts an interface slice into a mongo collection If you need to insert large quantities of items and every nanosecond matters, then use this function instead of Many.

func (*InsertQuery) One

func (iq *InsertQuery) One(objToInsert interface{}) (id *primitive.ObjectID, err error)

One is used to insert a single object into a collection

type Iter

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

Iter represents an iterator type. It is used to process the query result and unpack it into structs.

func (*Iter) All

func (iter *Iter) All(results interface{}) error

All unpacks all query results into the provided interface. The provided interface should be a list or a map.

func (*Iter) Close

func (iter *Iter) Close() error

Close closes the current cursor. This only needs to be called when using `.Next()` as `.All()` automatically closes the cursor in mongo-go-driver.

func (*Iter) Done

func (iter *Iter) Done() bool

Done is returned when there are no more results to be had from the cursor, whether from an error or otherwise

func (*Iter) Err

func (iter *Iter) Err() (err error)

Err returns an error should one have occurred while iterating. A note that timeout errors are also considered as part of this.

func (*Iter) Next

func (iter *Iter) Next(result interface{}) bool

Next iterates to the next value and unpacks it into the result struct

func (*Iter) TimedOut

func (iter *Iter) TimedOut() bool

TimedOut returns True if the request timed out.

type MongoConnectOptions

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

MongoConnectOptions holds helpers for configuring a new mongo connection.

type MongoErr

type MongoErr struct {
	Message string `json:"message"`
	// contains filtered or unexported fields
}

MongoErr represents any kind of mongo error, regardless of which component of mongo-go-driver threw the error.

func NewMongoErr

func NewMongoErr(err error) (me MongoErr)

NewMongoErr casts any error to a MongoErr. This is intended to help extrapolate all mongo errors into a single class. Should be used as:

if v := errors.Is(err, mongo.Error) {
		merr := NewMongoErr(err)
}

TODO: Should we be using this?

func (MongoErr) Error

func (me MongoErr) Error() string

func (MongoErr) Unwrap

func (me MongoErr) Unwrap() error

type ParsedQuery

type ParsedQuery struct {
}

type Plan

type Plan struct {
	Stage      string     `json:"stage"`
	InputStage InputStage `json:"inputStage"`
}

type Query

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

Query is used for creating To create a query, call a relevant function off of a Collection. The following line would return a *Query object:

`q := GetDatabase("db_name").C("collection_name").Find(bson.M{"alignment": "Chaotic Neutral"})`

And that can be consumed as such:

`var weirdCharacters []Character`
`err = q.Skip(5).Limit(10).Timeout(time.Minute).All(&weirdCharacters)``

The previous lines would: - Access db_name.collection_name - Setup the query filter(s) to skip the first 5 entries and limit to 10 entries max - timing out the query after 1 minute. - Run the find() query looking for records matching {"alignment": "Chaotic Neutral"} - Unpack the results into the weirdCharacters slice

func (*Query) Collation

func (q *Query) Collation(c *options.Collation) *Query

Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks. https://docs.mongodb.com/manual/reference/collation/ TODO: Create helpers and consts for Collation

func (*Query) Comment

func (q *Query) Comment(comment string) *Query

Comment adds a comment to the query - when the query is executed, this comment can help with debugging from the logs.

func (*Query) Hint

func (q *Query) Hint(indexKeys ...string) *Query

Hint allows a user to specify index key(s) and supplies these to .hint() - this can result in query optimization. This should either be the index name as a string or the index specification as a document. The following example would instruct mongo to use a field called 'age' as a look-up index. Mongo CLI: db.users.find().hint( { age: 1 } ) easymongo: err = conn.Collection(

"users").Find(bson.M{}).Hint("age").One(&userObj)

Reference: https://docs.mongodb.com/manual/reference/operator/meta/hint/ TODO: Support '-' prepending - shoul it be -1 or 0 as the value?

func (*Query) Sort

func (q *Query) Sort(fields ...string) *Query

Sort accepts a list of strings to use as sort fields. Prepending a field name with a '-' denotes descending sorting e.g. "-name" would sort the "name" field in descending order

func (*Query) Timeout

func (q *Query) Timeout(d time.Duration) *Query

Timeout uses the provided duration to set a timeout value using a context. The timeout clock begins upon query execution (e.g. calling .All()), not at time of calling Timeout().

type QueryPlanner

type QueryPlanner struct {
	PlannerVersion    string      `json:"plannerVersion"`
	Namespace         string      `json:"namespace"`
	IndexFilterSet    bool        `json:"indexFilterSet"`
	ParsedQuery       ParsedQuery `json:"parsedQuery"`
	QueryHash         string      `json:"queryHash"`
	PlanCacheKey      string      `json:"planCacheKey"`
	OptimizedPipeline bool        `json:"optimizedPipeline"`
	WinningPlan       Plan        `json:"winningPlan"`
	RejectedPlans     []Plan      `json:"rejectedPlans"`
}

type ReplaceQuery

type ReplaceQuery struct {
	*Query
	// contains filtered or unexported fields
}

ReplaceQuery is a helper for replacement query actions and options.

func (*ReplaceQuery) Execute

func (rq *ReplaceQuery) Execute() error

Execute runs the ReplaceQuery. No actions are taken until this query is run.

type UpdateQuery

type UpdateQuery struct {
	Query
	// contains filtered or unexported fields
}

UpdateQuery helps construct and execute update queries

func (*UpdateQuery) ArrayFilters added in v0.0.6

func (uq *UpdateQuery) ArrayFilters(o *options.ArrayFilters) *UpdateQuery

ArrayFilters is used to hold filters for the array filters CRUD option. If a registry is nil, bson.DefaultRegistry will be used when converting the filter interfaces to BSON. TODO: ArrayFilters helpers

func (*UpdateQuery) BypassDocumentValidation added in v0.0.6

func (uq *UpdateQuery) BypassDocumentValidation() *UpdateQuery

TODO: BypassDocumentValidation options docs

func (*UpdateQuery) Many added in v0.0.6

func (uq *UpdateQuery) Many() (matchedCount, updatedCount int, err error)

Many runs the UpdateQuery against all matching documents. No actions are taken until this function is called.

func (*UpdateQuery) One added in v0.0.6

func (uq *UpdateQuery) One() (err error)

One runs the UpdateQuery against the first matching document. No actions are taken until this function is called.

func (*UpdateQuery) UpdateOptions

func (uq *UpdateQuery) UpdateOptions() *options.UpdateOptions

UpdateOptions returns the native mongo driver options.UpdateOptions using the provided query information.

func (*UpdateQuery) Upsert added in v0.0.6

func (uq *UpdateQuery) Upsert() *UpdateQuery

Upsert specifies that if a document doesn't exist that matches the update filter, then a new document will be created as a result of this query run.

type UpdateQueryConstructor

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

UpdateQueryConstructor is a helper for easily crafting update queries. TODO: Support multiple calls to each block with unique field names, right now, calling .Increment().Increment() would only increment the last field

func (*UpdateQueryConstructor) AddToSet

func (qc *UpdateQueryConstructor) AddToSet(arrayFieldName string, objToAdd interface{}) *UpdateQueryConstructor

AddToSet pushes the provided interface{} object to the specified fieldname

func (*UpdateQueryConstructor) Decrement

func (qc *UpdateQueryConstructor) Decrement(fieldName string, i int) *UpdateQueryConstructor

Decrement decreases the specified field value by the provided int.

func (*UpdateQueryConstructor) Increment

func (qc *UpdateQueryConstructor) Increment(fieldName string, i int) *UpdateQueryConstructor

Increment increases the specified field value by the provided int.

func (*UpdateQueryConstructor) Match

func (qc *UpdateQueryConstructor) Match(query interface{}) *UpdateQueryConstructor

Match sets the Update query filter to the provided interface. If not specified, all documents will be updated.

func (*UpdateQueryConstructor) PopFirst

func (qc *UpdateQueryConstructor) PopFirst(arrayFieldName string) *UpdateQueryConstructor

PopFirst removes the first element from the specified array

func (*UpdateQueryConstructor) PopLast

func (qc *UpdateQueryConstructor) PopLast(arrayFieldName string) *UpdateQueryConstructor

PopLast removes the last element from the specified array

func (*UpdateQueryConstructor) Pull

func (qc *UpdateQueryConstructor) Pull(arrayFieldName string, pullCondition interface{}) *UpdateQueryConstructor

Pull pulls any array values that match the pullCondition query.

func (*UpdateQueryConstructor) PullAll

func (qc *UpdateQueryConstructor) PullAll(arrayFieldName string, pullCondition interface{}) *UpdateQueryConstructor

PullAll pulls any array values that match the pullCondition query. TODO: What is the difference between Pull and PullAll?

func (*UpdateQueryConstructor) Push

func (qc *UpdateQueryConstructor) Push(arrayFieldName string, objToPush interface{}) *UpdateQueryConstructor

Push pushes the specified object on to an array.

func (*UpdateQueryConstructor) Set

func (qc *UpdateQueryConstructor) Set(fieldName string, objToSet interface{}) *UpdateQueryConstructor

Set sets fieldName to the provided object. If you are looking to replace an entire document, consider using collection.Replace() instead. e.g. {"$set": {objToSet: objToSet}}

Jump to

Keyboard shortcuts

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