mongolang

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2022 License: Apache-2.0 Imports: 10 Imported by: 0

README

MonGolang

MongoDB

+ Golang

= Mon Golang

Goal

Simplify Go programs which use MongoDB. Create a library which supports the 10% of the calls which are needed 90% of the time, while easily allowing the use of the other 90% of MongoDB capabilities which are needed 10% of the time.

  1. Support the 10% of the calls which are used 90% of the time

  2. The other 90% of the calls which are used 10% of the time should be no more difficult to do then without this library

  3. Calls should resemble the calls made via the MongoDB Console

  4. Although error checking is important, it shouldn't get in the way of being able to chain calls such as:

      db.Coll("someCollection").
        Find(`{"lastName":"Johnson"}`).
        Sort(`{"firstName":1}`).
        Limit(5).
        Pretty()
    
  5. Don't extend the capabilities of the MongoDB Golang driver, just simplify the use of what's there

  6. New MongoDB releases should not require changes to the library or programs that use the library.

With Jupyter Notebook

Combined with Jupyter Notebook and GopherNotes, this provides a simple interface to run MongoDB Shell like commands using Go. Not only easy to iterate and easy to rerun, but also a great way to prototype code which can then be copied and pasted into a Go program. Below is an example query in Juptyter notebook using JSON strings.

Example 01 Using MonGolang in Jupyter Notebook Example 02 Using MonGolang in Jupyter Notebook

See here for a brief slide presentation on running MonGolang on Jupyter and then using the code in a standalone compiled Go program.

There is a PDF demo of the use of MonGolang in Jupyter in this repo at MonGolang_v0.2.1_Demo.pdf

There is also a PDF demo of the changes in release v0.2.2, which included support for insert and delete MongoDB Shell commands as well as a PrintBSON() and support for extended JSON at MonGolang_v0.2.2_Demo.pdf

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrClosedCursor = errors.New("call made to closed cursor for a method that requires an open cursor")
View Source
var ErrInvalidColl = errors.New("collection not linked to a properly established db")
View Source
var ErrInvalidCursor = errors.New("cursor not linked to a properly established collection")
View Source
var ErrNotConnected = errors.New("not connected to a MongoDB")
View Source
var ErrNotConnectedDB = errors.New("not connected to a MongoDB Database")
View Source
var ErrNotFindCursor = errors.New("method call requires a Find() cursor")

Functions

func Hello

func Hello(name string) string

Hello returns a greeting for the named person.

Example
fmt.Println(Hello("Doug"))
Output:

func PrintBSON

func PrintBSON(parm interface{})

PrintBSON prints formatted BSON structures, optionally with the value type.

Example
pipeline := `[
        { "$match" : {"_id" : {"$oid":"5bf36072a5820f6e28a4736c"} }},
		{ "$test" : "field that will be truncated because of length" },
		{ "$test" : ["an array", "of text", "values"]},
		{ "$test" : [{"array": "of"}, {"objects": 2}]},
		{ "$limit": 3 }
	]`

var doc interface{}
err := bson.UnmarshalExtJSON([]byte(pipeline), true, &doc)
if err != nil {
	panic(err)
}

PrintBSON(doc)
Output:

[{
      $match (D): {
         _id (ObjectID): ObjectID("5bf36072a5820f6e28a4736c")
      }
   },
   {
      $test (string): field that will be truncated b...
   },
   {
      $test (A): [an array, of text, values]
   },
   {
      $test (A): [{
            array (string): of
         },
         {
            objects (int32): 2
         }
      ]
   },
   {
      $limit (int32): 3
   }
 ]

func PrintStruct

func PrintStruct(s interface{})

PrintStruct prints an interface object as "pretty" json

Example
// bsonD := bson.D{{Key: "bsonDKey", Value: "bsonDValue"}}
bsonD := bson.D{{Key: "bsonDKey", Value: "bsonDValue"}}
PrintStruct(bsonD)
Output:

[
  {
    "Key": "bsonDKey",
    "Value": "bsonDValue"
  }
]

Types

type Coll

type Coll struct {
	DB        *DB
	MongoColl *mongo.Collection
	CollName  string
}

Coll represents a collection

func (*Coll) Aggregate

func (c *Coll) Aggregate(pipeline interface{}, parms ...interface{}) *Cursor

Aggregate returns a cursor for an aggregation pipeline operation. The pipeline passed can be one of: []bson.D, bson.A, string If bson.A, each entry must be a bson.D If string, must be a valid JSON doc that parses to a valid bson.A

func (*Coll) DeleteMany

func (c *Coll) DeleteMany(filter interface{}, opts ...interface{}) *mongo.DeleteResult

DeleteMany can delete many documents with one call as specified by the filter TODO: implement delete options.

func (*Coll) DeleteOne

func (c *Coll) DeleteOne(filter interface{}, opts ...interface{}) *mongo.DeleteResult

DeleteOne deletes a single document. Note that the filter need not specify a single document but only one document will be deleted. TODO: implement delete options.

func (*Coll) Err

func (c *Coll) Err() error

Return any errors or nil if no error

func (*Coll) Find

func (c *Coll) Find(parms ...interface{}) *Cursor

Find returns a Cursor Parms are optional. If present, the following parms are recognized:

	parms[0] - query - bson.M defines of which documents to select
 parms[1] - projection - bson.D defines which fields to retrieve

func (*Coll) FindOne

func (c *Coll) FindOne(parms ...interface{}) *bson.D

FindOne returns a single MongoDB Document All parms are optional. If present, the following parms are recognized:

	parms[0] - query - bson.M or bson.D defines of which documents to select
 parms[1] - projection - bson.M or bson.D defines which fields to retrieve

func (*Coll) InsertMany

func (c *Coll) InsertMany(documents interface{}, opts ...interface{}) *mongo.InsertManyResult

InsertMany inserts a slice of documents into a Collection. Documents must be a slice or bson.A of bson.D documents TODO: implement insert one options

func (*Coll) InsertOne

func (c *Coll) InsertOne(document interface{}, opts ...interface{}) *mongo.InsertOneResult

InsertOne inserts one document into the Collection. Document must be a bson.D or bson.M. TODO: implement insert one options

func (*Coll) NewCursor

func (c *Coll) NewCursor() *Cursor

NewCursor creates a new cursor for this collection

type Cursor

type Cursor struct {
	Collection   *Coll
	MongoCursor  *mongo.Cursor
	IsClosed     bool
	IsFindCursor bool

	NextDoc *bson.D

	Filter      interface{}
	FindOptions options.FindOptions

	AggrPipeline interface{}
	AggrOptions  options.AggregateOptions
}

Cursor represents a cursor for a Collection

func (*Cursor) Close

func (c *Cursor) Close() error

Close closes a cursor Note that it's possible to reuse the cursor, though not recommended?

func (*Cursor) Count

func (c *Cursor) Count() int

Count returns a count of the (remaining) documents for the cursor.

func (*Cursor) Err

func (c *Cursor) Err() error

If there is an error, return it. Else returns nil.

func (*Cursor) ForEach

func (c *Cursor) ForEach(f func(*bson.D))

ForEach calls the specified function once for each remaining cursor document passing the function a bson.D document.

func (*Cursor) HasNext

func (c *Cursor) HasNext() bool

HasNext returns true if the cursor has a next document available.

func (*Cursor) Limit

func (c *Cursor) Limit(limitCount int64) *Cursor

Limit specifies the max number of documents to return

func (*Cursor) Next

func (c *Cursor) Next() *bson.D

Next returns the next document for the cursor as a bson.D struct. TODO: allow a struct to be passed similar to cursor.ToArray(...)

func (*Cursor) Pretty

func (c *Cursor) Pretty() string

Pretty returns a pretty string version of the remaining documents for a cursor. Unlike String() it shows the bson.D as key:value instead of {Key:key Value:value}

func (*Cursor) Skip

func (c *Cursor) Skip(skipCount int64) *Cursor

Skip specifies the number of documents to skip before returning the first document

func (*Cursor) Sort

func (c *Cursor) Sort(sortSequence interface{}) *Cursor

Sort specifies the bson.D to be used to sort the cursor results

func (*Cursor) String

func (c *Cursor) String() string

String fulfills the Stringer interface. Calling this will return a string containing the "pretty" print contents of the ToArray() function. ToArray() returns an array with all of the documents remaining for the cursor and closes the cursor.

func (*Cursor) ToArray

func (c *Cursor) ToArray(parm ...interface{}) []bson.D

ToArray returns all of the remaining documents for a cursor in a bson.D slice. NOTE: currently seems to return all docs even those already read via a cursor.Next() call. Optional parm is a pointer to a slice which typically would contain a custom struct or bson.A struct. In this case, ToArray returns an empty []bson.D slice. This may change at some future date but currently it is difficult to deal with a slice of any type. For consistency with Mongo Shell ToArray should return a slice. However we also need the ability to return all of the documents to a slice which is a custom struct or a bson.A struct.

type DB

type DB struct {
	Client *mongo.Client

	Err error

	Database *mongo.Database
	Name     string
}

DB struct defines the fields necessary to track the state of a connection to a MongoDB server

func (*DB) Coll

func (mg *DB) Coll(collectionName string) *Coll

Coll returns a collection for a given name If there was a previous error don't set coll.MongoColl

func (*DB) Disconnect

func (mg *DB) Disconnect()

Disconnect disconnects the MongoDB and cleans up any other resources, resetting the MonGolang structure

func (*DB) InitMonGolang

func (mg *DB) InitMonGolang(connectionURI string) *DB

InitMonGolang initializes the connection to the MongoDB Database

func (*DB) ShowCollections

func (mg *DB) ShowCollections() []string

ShowCollections returns a list of collections for current Database

func (*DB) ShowDBs

func (mg *DB) ShowDBs() []string

ShowDBs returns a list of Database Names

func (*DB) Use

func (mg *DB) Use(dbName string) *DB

Use connects the MongoDB Client to the specified Database. The MonGolangDB needs to be inialized via mg.InitMonGolang() before calling this method.

Jump to

Keyboard shortcuts

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