mongo

package module
v0.1.6 Latest Latest
Warning

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

Go to latest
Published: Aug 31, 2022 License: MIT Imports: 9 Imported by: 9

README

go-mongo

Go Reference

A library exposing an implementation of mongodb/mongo-go-driver.

You can configure the client URL and start interacting with the mongo db database without worrying about managing database connections. Every endpoint instantiates a database client and is independent of each other. Every endpoint can also be worked on a pool of go routines bringing concurrency benefits.

What is MongoDB?

MongoDB is a document based database service. It has a cloud-oriented product called MongoDB Atlas which handles the replication strategy without external effort. The schema is not required to be defined as the documents can contain anything.

Learning outcomes

  • Configure Mongo DB Atlas database using the client url.
  • Write, Update and Delete mongo document object using identifiers, wherever applicable.
  • Filtering and sorting documents to a cursor response.
  • Parsing a list response using a document cursor.

Installation

The recommended way to get started using the MongoDB Go driver is by using go modules to install the dependency in your project. This can be done either by importing packages from go-mongo and having the build step install the dependency or by explicitly running

go get github.com/atulanand206/go-mongo

Pre-requisites

  • Mongo Client URL should be configured for the cluster of your choice.
  • Database and Collection must be created on the database.

How to implement

  • Define the required variables in the environment
mongoClientId := os.Getenv("MONGO_CLIENT_ID")
database = os.Getenv("DATABASE")
collection = os.Getenv("MONGO_COLLECTION")
  • Configure the client before using any of the endpoints.
mongo.ConfigureMongoClient(mongoClientId)
Examples of bson documents
  • bson.D: Convert an object to an ordered representation a bson document.
document, err := mongo.Document(&object)
if err != nil {
    log.Print(err)
    return
}
  • bson.M: An unordered representation of a bson document.
filter := bson.M{"name": name}
  • FindOptions: Object used for specifying sort and additional criteria.
opts := options.Find()
opts.SetSort(bson.D{primitive.E{Key: "rating", Value: -1}})
Examples of endpoints
  • Write a document to the mongo collection.
mongo.Write(database, collection, *document)
  • Update a document in the mongo collection based on filter criteria.
mongo.Update(database, collection, filter, *document)
  • Delete a document from the mongo collection based on filter criteria.
mongo.Delete(database, collection, filter, *document)
  • Find documents based on filters and options. The decoding depends on the actual definition of the object and hence required with the implementation.
cursor, err := mongo.Find(database, collection, filter, opts)
for cursor.Next(context.Background()) {
    var object Object
    err := cursor.Decode(&object)
    if err != nil {
        log.Print(err)
        return
    }
    response = append(response, object)
}
  • Find a document based on filters and decode to object. First item is returned if multiple documents match the criteria.
response := mongo.FindOne(database, collection, filter)
var object Object
if err = response.Decode(&object); err != nil {
    log.Print(err)
    return
}

Author

  • Atul Anand

License

The MongoDB Go Driver is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Document

func Document(request interface{}) (doc bson.M, err error)

Types

type DB added in v0.1.5

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

func (*DB) Create added in v0.1.5

func (db *DB) Create(request interface{}, collection string) (err error)

func (*DB) CreateCollection added in v0.1.5

func (db *DB) CreateCollection(collection string) error

func (*DB) CreateMany added in v0.1.5

func (db *DB) CreateMany(request []interface{}, collection string) (err error)

func (*DB) DecodeRaw added in v0.1.5

func (db *DB) DecodeRaw(cursor *mg.Cursor) (documents []bson.Raw, err error)

func (*DB) Delete added in v0.1.5

func (db *DB) Delete(collection string, identifier bson.M) (result *mg.DeleteResult, err error)

func (*DB) Find added in v0.1.5

func (db *DB) Find(collection string, filters bson.M, findOptions *options.FindOptions) (result []bson.Raw, err error)

func (*DB) FindOne added in v0.1.5

func (db *DB) FindOne(collection string, filters bson.M, findOptions *options.FindOneOptions) (result bson.Raw, err error)

func (*DB) Update added in v0.1.5

func (db *DB) Update(collection string, identifier bson.M, doc interface{}) (result *mg.UpdateResult, err error)

type DBConn added in v0.1.5

type DBConn interface {
	CreateCollection(collection string) error
	Create(request interface{}, collection string) (err error)
	CreateMany(request []interface{}, collection string) (err error)
	FindOne(collection string, filters bson.M, findOptions *options.FindOneOptions) (result bson.Raw, err error)
	Find(collection string, filters bson.M, findOptions *options.FindOptions) (result []bson.Raw, err error)
	Delete(collection string, identifier bson.M) (result *mg.DeleteResult, err error)
	Update(collection string, identifier bson.M, doc interface{}) (result *mg.UpdateResult, err error)
}

func NewDb added in v0.1.5

func NewDb(dbName string) DBConn

func NewMockDb added in v0.1.6

func NewMockDb() DBConn

type MockDB added in v0.1.6

type MockDB struct {
	Data map[string]map[interface{}]interface{}
}

func (*MockDB) Create added in v0.1.6

func (db *MockDB) Create(request interface{}, collection string) (err error)

func (*MockDB) CreateCollection added in v0.1.6

func (db *MockDB) CreateCollection(collection string) error

func (*MockDB) CreateMany added in v0.1.6

func (db *MockDB) CreateMany(request []interface{}, collection string) (err error)

func (*MockDB) Delete added in v0.1.6

func (db *MockDB) Delete(collection string, identifier bson.M) (result *mg.DeleteResult, err error)

func (*MockDB) Find added in v0.1.6

func (db *MockDB) Find(collection string, filters bson.M, findOptions *options.FindOptions) (results []bson.Raw, err error)

func (*MockDB) FindOne added in v0.1.6

func (db *MockDB) FindOne(collection string, filters bson.M, findOptions *options.FindOneOptions) (result bson.Raw, err error)

func (*MockDB) Update added in v0.1.6

func (db *MockDB) Update(collection string, identifier bson.M, v interface{}) (result *mg.UpdateResult, err error)

type MongoClient added in v0.1.2

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

func NewMongoClient added in v0.1.5

func NewMongoClient(url string, dbName string) *MongoClient

func (*MongoClient) CreateCollection added in v0.1.2

func (mongoClient *MongoClient) CreateCollection(collection string, options *options.CreateCollectionOptions) error

func (*MongoClient) CreateCollections added in v0.1.2

func (mongoClient *MongoClient) CreateCollections(collections []string) error

Creates collections with given names

func (*MongoClient) Delete added in v0.1.2

func (mongoClient *MongoClient) Delete(collection string, identifier bson.M) (*mongo.DeleteResult, error)

Deletes the documents from the specified database and collection based on identifier filter. Returns the id of the document upon delete if one entry or the count information if many. If delete fails, returns an error otherwise. Client must be configured to use this endpoint.

func (*MongoClient) Disconnect added in v0.1.2

func (mongoClient *MongoClient) Disconnect()

func (*MongoClient) Document added in v0.1.2

func (mongoClient *MongoClient) Document(v interface{}) (doc *bson.D, err error)

Converts a struct to the bson document used for inserting document.

func (*MongoClient) DropCollections added in v0.1.2

func (mongoClient *MongoClient) DropCollections(collections []string) error

Drops collections with given names

func (*MongoClient) Find added in v0.1.2

func (mongoClient *MongoClient) Find(collection string, filter bson.M, options *options.FindOptions) (*mongo.Cursor, error)

Finds a cursor of the documents based on the filter and filter options from the specified database and collection. Returns the documents upon search and error otherwise. Client must be configured to use this endpoint.

func (*MongoClient) FindOne added in v0.1.2

func (mongoClient *MongoClient) FindOne(collection string, filter bson.M, options *options.FindOneOptions) *mongo.SingleResult

Finds a document based on the filter from the specified database and collection. Client must be configured to use this endpoint.

func (*MongoClient) GetMongoClient added in v0.1.2

func (mongoClient *MongoClient) GetMongoClient(clientUrl string) *mongo.Client

Returns the db client of the attached client url.

func (*MongoClient) Update added in v0.1.2

func (mongoClient *MongoClient) Update(collection string, identifier bson.M, change bson.D) (*mongo.UpdateResult, error)

Updates the documents to the specified database and collection based on identifier filter. Returns the id of the document upon update if one entry or the count information if many. If update fails, returns an error otherwise. Client must be configured to use this endpoint.

func (*MongoClient) Write added in v0.1.2

func (mongoClient *MongoClient) Write(collection string, doc bson.D) (*mongo.InsertOneResult, error)

Inserts a document to the specified database and collection. Returns the id of the document upon creation and error otherwise. Client must be configured to use this endpoint.

func (*MongoClient) WriteMany added in v0.1.2

func (mongoClient *MongoClient) WriteMany(collection string, doc []interface{}) (*mongo.InsertManyResult, error)

Inserts many documents to the specified database and collection. Returns the id of the documents upon creation and error otherwise. Client must be configured to use this endpoint.

Jump to

Keyboard shortcuts

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