gomango

package module
v0.0.0-...-0ec70aa Latest Latest
Warning

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

Go to latest
Published: May 1, 2019 License: GPL-3.0 Imports: 4 Imported by: 0

README

gomango

A utility to use on top of mgo to ease the process of making Mongo queries in Go

Getting Started

Clone this repository into your project folder residing in the src folder of your GOPATH. See Writing Go Code for more information.

Update queries.go with your MongoDB details and credentials.

Import the package gomango into the code wherever required like this

import <project package>/gomango

Inside your main project package's init function, add the following initialization command -

gomango.DatabaseInit()

That's it.

Prerequisites

You need mgo or a related mongodb driver for Go installed. You can install mgo with the following command

go get gopkg.in/mgo.v2

If you have mgo installed, you can use this out of the box. If you want to use this with a driver other than mgo, you will need to update the MgoSession variable with the relevant value as mentioned in that driver's documentation.

MgoSession      *mgo.Session
Usage example

GoMango's main purpose is to simplify the purpose of making MongoDB queries.

For e.g., Instead of

results := *mgo.Session.DB(testdb).C(testcollection).Find(bson.M{"isActive": true}).Sort("title").All()

with GoMango, you can do

results := gomango.GetSortedResults("testcollection", bson.M{"isActive": true}, "title")

which will return the same results, i.e. all objects with field 'isActive' being true, sorted by their 'title' fields from 'testcollection'

List of functions with examples

  • GetResults - GetResults function will return all results for a given query.
results := gomango.GetResults("testcollection", bson.M{"field1": "value1", "field2": "value2"})
  • GetSortedResults - GetSortedResults function will return results sorted as per sorting criteria.
results := gomango.GetSortedResults("testcollection", bson.M{"field1": true, "field2": "value2"}, "field3")
  • GetFields - GetFields function uses a projection to show only those fields that are required. Returns all matching fields.
results := gomango.GetFields("testcollection", bson.M{"field1": "value1"}, bson.M{"field_to_be_included_1": 1, "field_to_be_included_2": 1, "field_to_be_excluded": 0})
  • GetMappedFields - GetMappedFields is similar to GetResults but returns an array of maps instead of an array of interfaces.
results := gomango.GetMappedFields("testcollection", bson.M{"field1": "value1"}, "field_to_be_included": 1})
  • GetMappedFieldsWithLimit - GetMappedFieldsWithLimit is similar to GetMappedFields but uses Limit and Iter to return only the number of results that are required.
results := gomango.GetMappedFieldsWithLimit("testcollection", bson.M{"field1": "value1", "field2": "value2", "field3_bool": true, "field4_should_not_exist": bson.M{"$exists": false}, "field5_in_given_array": bson.M{"$in": []string{"arr_val1", "arr_val2", "arr_val3"}}}, bson.M{"field_to_be_included": 1}, 5)
  • GetSortedResultsMap - GetSortedResultsMap function will return results sorted as per sorting criteria in the form of an array of maps.
results := gomango.GetSortedResultsMap("testcollection", bson.M{"field1": "value1", "field2": "value2", "field3_bool": true}, "-createdAt")
// Sorts by descending order of field named 'createdAt'
  • GetSortedMappedFields - GetSortedMappedFields function will return only the requested fields sorted as per sorting criteria in the form of an array of maps.
results := gomango.GetSortedMappedFields("testcollection", bson.M{"field1_only_if_exists": bson.M{"$exists": true}, "field2": "value2", "field4_not_in_given_array": bson.M{"$not": bson.M{"$in": []string{"arr_val1", "arr_val2", "arr_val3"}}}}, bson.M{//leave blank to include all fields}, "-sort_by_field_name_without_quotes")
  • DeleteFields - DeleteFields is actually an Update operation but can delete whole documents as well.
results := gomango.DeleteFields("testcollection", bson.M{"identifier_field1": "value1", bson.M{"$pull": bson.M{"could_be_an_array_field": bson.M{"_id": bson.ObjectIdHex(ID_val)}}})
  • RemoveDocument - RemoveDocument to remove all documents matching given conditions. Avoid using DeleteFields for this purpose.
err := gomango.RemoveDocument("testcollection", bson.M{"field1": "value1"})
  • GetResultsById - GetResultsById is a variant of GetResults which returns one result - matching a given set of criteria, which is supposed to be an ID. This function could be modified in later versions to match only ID as that's a frequent requirement in MongoDB-backed data.
results := gomango.GetResultsById("testcollection", bson.M{"field1": "value1"})
  • InsertDocument - InsertDocument function accepts any number of queries to insert to a document. Returns success or failure as boolean.
err := gomango.InsertDocument("testcollection", bson.M{"field1": "value1"})
  • UpsertCollection - UpsertCollection is a standard Upsert operation. Returns changeInfo and error.
_, err := gomango.UpsertCollection("testcollection", bson.M{"field1": "value1"}, bson.M{"field1": "value1_2", "field2": "value2"})
  • FindOneDocument - FindOneDocument is a lot like GetResultsById but the return type here is map[string]interface{} instead of just an interface{}.
result := gomango.FindOneDocument("testcollection", bson.M{"field1": "value1", "field2":  "value2",})
  • FindDocuments - FindDocuments is an 'All' variant of FindOneDocument. Returns all matching results as an array of maps.
results := gomango.FindDocuments("testcollection", bson.M{"field1": "value1", "field2":  "value2",})
  • UpdateDocument - UpdateDocument will update fields matching the given query. Use $set with this to retain other fields.
err := gomango.UpdateDocument("testcollection", bson.M{"field1": "value1"}, bson.M{"$set": map[string]map[string]string{"field2": map[string]string{"sub_field1": "value_sub_field_1", "sub_field2": "value_sub_field_2"}}})
  • GetCount - GetCount returns the count of results of a given query.
count, err := gomango.GetCount("testcollection", bson.M{"field1": "value1"})
  • Aggregation - Aggregation function provides a medium to use the MongoDB Aggregation Framework. Can be used in many different ways by supplying an array of queries as the second parameter.

  • Distinct - Distinct function to return distinct records for a given field in a query.

results := gomango.Distinct("testcollection", bson.M{"field1": "value1", "field2": "field2"}, "distinct_field")
  • FindAndModify - FindAndModify function to find and modify in a single step. Returns count of items modified, information of the modification and an error if there.
count, _, err := gomango.FindAndModify("testcollection", bson.M{"field1": "value1"}, bson.M{"$inc": bson.M{"field2": "value2"}})

Miscellaneous

I've included comments for every function and every major variable/constant used in the file. You are free to modify the existing functions to create your own functions

Contributing

Feel free to submit a pull request or fork this repository as per your preferences in order to improve on this utility.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Acknowledgments

  • Many thanks to Abhishek for helping me learn Go and showing me the first examples of functions in to-be GoMango. He's a great guy!
  • Many many thanks to Saddy for inspiring me to start this project.

Documentation

Index

Constants

View Source
const (
	MongoDBHosts = "127.0.0.1:27017" // MongoDBHosts is your MongoDB URL.
	AuthDatabase = "admin"           // The database that contains the authorization credentials for your MongoDB database. Leave this and all further fields blank if you're running MongoDB without authentication.
	AuthUserName = "user"            // The user through which you would like to access your MongoDB database. This user could have read or write access or both. In case it has only read access, some of GoMongo's functions may result in failure.
	AuthPassword = "password"        // The password for the user which has authenticated access to your MongoDB database.
	TestDatabase = "testdb"          // This constant holds the name of a test database, so that you can quickly change from the main DB to a test DB using the Dbname variable below.Aggregation

)

Variables

View Source
var (
	MgoSession *mgo.Session
	Dbname     = "targetdb" // Database that contains the actual information that is required to be queried.

)

Functions

func Aggregation

func Aggregation(collectionName string, aggregationquery []bson.M) (result []map[string]interface{})

Aggregation function provides a medium to use the MongoDB Aggregation Framework.

func DatabaseInit

func DatabaseInit()

DatabaseInit function initializes the database connection.

func DeleteFields

func DeleteFields(collectionName string, selector interface{}, updater interface{}) bool

DeleteFields is actually an Update operation but can delete whole documents as well.

func Distinct

func Distinct(collectionName string, query interface{}, field string) (result []interface{})

Distinct function to return distinct records for a given field in a query.

func FindAndModify

func FindAndModify(collectionName string, find interface{}, modify interface{}) (result, info interface{}, err error)

FindAndModify function to find and modify in a single step

func FindDocuments

func FindDocuments(collectionName string, query interface{}) (result []map[string]interface{})

FindDocuments is an 'All' variant of FindOneDocument. Returns all matching results as an array of maps.

func FindOneDocument

func FindOneDocument(collectionName string, query interface{}) (result map[string]interface{})

FindOneDocument is a lot like GetResultsById but the return type here is map[string]interface{} instead of just an interface{}.

func GetCount

func GetCount(collectionName string, selector interface{}) (int, error)

GetCount returns the count of results of a given query.

func GetFields

func GetFields(collectionName string, query interface{}, selector interface{}) (result []interface{})

GetFields function uses a projection to show only those fields that are required. Returns all matching fields.

func GetMappedFields

func GetMappedFields(collectionName string, query interface{}, selector interface{}) (result []map[string]interface{})

GetMappedFields is similar to GetResults but returns an array of maps instead of an array of interfaces.

func GetMappedFieldsWithLimit

func GetMappedFieldsWithLimit(collectionName string, query interface{}, selector interface{}, limit int) (result []map[string]interface{})

GetMappedFieldsWithLimit is similar to GetMappedFields but uses Limit and Iter to return only the number of results that are required.

func GetResults

func GetResults(collectionName string, query interface{}) (result []interface{})

GetResults function will return all results for a given query.

func GetResultsById

func GetResultsById(collectionName string, query interface{}) (result interface{})

GetResultsById is a variant of GetResults which returns one result - matching a given set of criteria, which is supposed to be an ID. This function could be modified in later versions to match only ID as that's a frequent requirement in MongoDB-backed data.

func GetSortedMappedFields

func GetSortedMappedFields(collectionName string, query interface{}, selector interface{}, sortingcriteria string) (result []map[string]interface{})

GetSortedMappedFields function will return only the requested fields sorted as per sorting criteria in the form of an array of maps.

func GetSortedResults

func GetSortedResults(collectionName string, query interface{}, sortingcriteria string) (result []interface{})

GetSortedResults function will return results sorted as per sorting criteria.

func GetSortedResultsMap

func GetSortedResultsMap(collectionName string, query interface{}, sortingcriteria string) (result []map[string]interface{})

GetSortedResultsMap function will return results sorted as per sorting criteria in the form of an array of maps.

func InsertDocument

func InsertDocument(collectionName string, query ...interface{}) bool

InsertDocument function accepts any number of queries to insert to a document. Returns success or failure as boolean.

func RemoveDocument

func RemoveDocument(collectionName string, selector interface{}) (err error)

RemoveDocument to remove all documents matching given conditions. Avoid using DeleteFields for this purpose.

func UpdateDocument

func UpdateDocument(collectionName string, selector interface{}, update interface{}) (err error)

UpdateDocument will update fields matching the given query. Use $set with this to retain other fields.

func UpsertCollection

func UpsertCollection(collectionName string, selector interface{}, update interface{}) (info *mgo.ChangeInfo, err error)

UpsertCollection is a standard Upsert operation. Returns changeInfo and error.

Types

This section is empty.

Jump to

Keyboard shortcuts

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