arnaucube
arnaucube/goBlockchainDataAnalysisPublic Self-hosted repository
goBlockchainDataAnalysis/mongoOperations.go
mongoOperations.goRaw
 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"io/ioutil"
 7	"log"
 8
 9	mgo "gopkg.in/mgo.v2"
10	"gopkg.in/mgo.v2/bson"
11)
12
13//MongoConfig stores the configuration of mongodb to connect
14type MongoConfig struct {
15	Ip       string `json:"ip"`
16	Database string `json:"database"`
17}
18
19var mongoConfig MongoConfig
20
21func readMongodbConfig(path string) {
22	file, e := ioutil.ReadFile(path)
23	if e != nil {
24		fmt.Println("error:", e)
25	}
26	content := string(file)
27	json.Unmarshal([]byte(content), &mongoConfig)
28}
29
30func getSession() (*mgo.Session, error) {
31	session, err := mgo.Dial("mongodb://" + mongoConfig.Ip)
32	if err != nil {
33		panic(err)
34	}
35	//defer session.Close()
36
37	// Optional. Switch the session to a monotonic behavior.
38	session.SetMode(mgo.Monotonic, true)
39
40	// Optional. Switch the session to a monotonic behavior.
41	session.SetMode(mgo.Monotonic, true)
42
43	return session, err
44}
45func getCollection(session *mgo.Session, collection string) *mgo.Collection {
46
47	c := session.DB(mongoConfig.Database).C(collection)
48	return c
49}
50func saveBlock(c *mgo.Collection, block BlockModel) {
51	//first, check if the item already exists
52	result := BlockModel{}
53	err := c.Find(bson.M{"hash": block.Hash}).One(&result)
54	if err != nil {
55		//item not found, so let's add a new entry
56		err = c.Insert(block)
57		check(err)
58	} else {
59		err = c.Update(bson.M{"hash": block.Hash}, &block)
60		if err != nil {
61			log.Fatal(err)
62		}
63	}
64
65}