Skip to content

Mongo leaf is a simple tool between you and go-mongodb driver. in leaf we only use json format to use mongo just like mongo-shell if you have a dynamic scenario mongo leaf might be useful for you.

License

Notifications You must be signed in to change notification settings

aamirmousavi/mongoleaf

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

33 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Mongo Leaf

Mongo leaf is a simple tool between you and go-mongodb driver. in leaf we only use json format to use mongo just like mongo-shell if you have a dynamic scenario mongo leaf might be useful for you. I'm noob in go and programing sorry for bad explantion so I tryed to make anything simple for noobs like me.

Contents

Install

first execute this command

    go get github.com/aamirmousavi/mongoleaf

then in your go code import leaf package

import (
   "github.com/aamirmousavi/mongoleaf"
)

Create Connetion

for connect to mongodb

    client, err := mongoleaf.New("mongodb://localhost:27017")
    if err != nil {
        //deal with error
	}

put your mongo URL as an argument for make connetion with your database

Create Database

in your mongodb client if you want to create or refrence to a database you would use DataBase Function just like this for making a refrence to your database

    client, err := mongoleaf.New("mongodb://localhost:27017")
    if err != nil {
         //deal with error
    }
    myDataBase := client.DataBase("myDBName")

now you can esly access the colletions and function of each database you have

Create Colletion

as you now in mongo each database might have many collations so when you define a database you can call or create a collation in that database just like this example

myCollation := client.DataBase("DbName").Colletion("myCollation")

if database or colletion you calling is not exsists it will create them

Simple Example

package main

import (
	"fmt"

	"github.com/aamirmousavi/mongoleaf"
)

func main() {
	client, err := mongoleaf.New("mongodb://localhost:27017")
	if err != nil {
		panic(err)
	}

	siteDB := client.DataBase("website")
	products := siteDB.Colletion("products")

	products.InsertMany(`[
		{
		"title":"pro_1",
		"price":5
	}, {
		"title":"pro_2",
		"price":2
	}, {
		"title":"pro_3",
		"price":15
	}
	]`, "")

    //simple index
	products.CreateIndex(`{
		"Keys":{
			"price":1
		},
		"Options":{
			"Name":"myPriceIndex"
		}
	}`, ``)
    
	//first arg is filter that mongo filter rows and second is the update you want to set
	//and last is option if you don't have any option use empty string or empty json map: "" or "{}"
	result, err := products.UpdateMany(`{
		"price":{
			"$gt":10
		}
	}`, `{
		"$set":{
			"more_than_10":true
		}
	}`, "")

	fmt.Printf("update \n\terror: %v \n\tresult: %v \n", err, result)

	//if your filter is "{}" you can also use empty string as no filter
	//it will return all rows in a colletion
	rows, err := products.Find("", "")
	jsonRows := mongoleaf.JSONPretty(rows)
	fmt.Printf("find result \n\terror: %v \n\trows: %v \n", err, jsonRows)
}

OutPut

update 
        error: <nil> 
        result: map[MatchedCount:1 ModifiedCount:1 UpsertedCount:0 UpsertedID:<nil>] 
find result 
        error: <nil> 
        rows: [
        {
                "_id": "61e4bf46d16388a583426754",
                "price": 5,
                "title": "pro_1"
        },
        {
                "_id": "61e4bf46d16388a583426755",
                "price": 2,
                "title": "pro_2"
        },
        {
                "_id": "61e4bf46d16388a583426756",
                "more_than_10": true,
                "price": 15,
                "title": "pro_3"
        }
 ] 

Functions

  • Client Functions

    you always able to use dirvers functions like start session or watch and extra like this example

        client, err := mongoleaf.New("mongodb://localhost:27017")
        if err != nil {
            panic(err)
        }
        dbNames, err := client.Client.StartSession(&options.SessionOptions{})

    just add .Client and call your functions also this works for database and colletion not only client type

    • Connect

          client, err := mongoleaf.New("mongodb://localhost:27017")
          if err != nil {
              panic(err)
          }
          err = client.Connect()
    • Disconnect

          err = client.Disconnect()
    • ListDatabaseNames

          filter, option := `{}`, `{}` //empty filter return all 
          dbNames, err := client.ListDatabaseNames(filter, option)
    • ListDatabases

      reutrn a array of maps with Name, Empty and SizeOnDisk keys

          dataBases, err := client.ListDatabases(filter, option)
  • Database Functions

    • Aggregate

          out, err := client.DataBase(dbName).Aggregate(pipline, option)
    • Drop

          err := client.DataBase(dbName).Drop()
    • CreateCollection

      err := client.DataBase(dbName).CreateCollection("colName")
    • CreateView

      err := client.DataBase(dbName).CreateView(viewName, viewOn, pipline, option)
    • ListCollectionNames

      colNames, err := client.DataBase(dbName).ListCollectionNames(filter, option)
    • ListCollections

      colNames, err := client.DataBase(dbName).ListCollections(filter, option)
    • RunCommand

      out, err := client.DataBase(dbName).RunCommand(Command, option)
    • RunCommandCursor

      res, err := client.DataBase(dbName).RunCommandCursor(Command, option)
  • Colletion Functions

    • Find

      for reading many recoard in a mongo colletion

      myCollation := client.DataBase("DbName").Colletion("myCollation")
      filter:=`{"title":"my title"}`  //just like mongoshell filter
      options:=`{"limit":2}`           //just like mongoshell option
      results, err := myCollation.Find(filter,options)

      it's retrun an array of maps if you want json result you can parse any type to json with mongoleaf.JSON function

      json := mongoleaf.JSON(results)

      for reading only one reacord

      results, err := myCollation.FindOne(`{"title":"my title"}`,``)

      as you see we don't have any option we should pass empty "" or `{}` as option also if you have empty filter you can use empty string "" or `{}` as filter

    • Aggregate

      results, err := myCollation.Aggregate(`[{},{}]`,``) 

      as you know in mongodb Aggregate has array of map style so keep it in mind

    • Update

      result, err := myCollation.UpdateMany(`{"_id":"sd1d12ds12d..."}`,`{"title":"new title"}`,option) 
    • Delete

      for deleteing many recoards use DeleteMany fountion

      result, err := client.DataBase("DbName").Colletion("myCollation").DeleteMany(`{"_id":"sd12d12d2123"}`,option)

      as you see we called it in defrent way you can call all CRUD fountions just like this code

      result, err := myCollation.DeleteOne(`{"_id":"sd1d12ds12d..."}`,option) 
    • Insert

      for inserting if you are using insert many you have to insert your rows in an array parent

      result, err := myCollation.InsertMany(`[
          {"title":"the title 1"},
          {"title":"the title 12"},
          {"title":"the title 2"}
          ]`,option) 

      for insetring one row

      result, err := myCollation.InsertOne(`{"title":"the title 1"}`,option) 
    • FindOneAnd

    • CountDocuments

    • Distinct

    • Drop

    • EstimatedDocumentCount

About

Mongo leaf is a simple tool between you and go-mongodb driver. in leaf we only use json format to use mongo just like mongo-shell if you have a dynamic scenario mongo leaf might be useful for you.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages