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}
66
67func getAllNodes() ([]NodeModel, error) {
68 result := []NodeModel{}
69 iter := nodeCollection.Find(bson.M{}).Limit(500).Iter()
70 err := iter.All(&result)
71 return result, err
72}
73
74func saveNode(c *mgo.Collection, node NodeModel) {
75 //first, check if the node already exists
76 result := NodeModel{}
77 err := c.Find(bson.M{"id": node.Id}).One(&result)
78 if err != nil {
79 //node not found, so let's add a new entry
80 err = c.Insert(node)
81 check(err)
82 } else {
83 err = c.Update(bson.M{"id": node.Id}, &node)
84 if err != nil {
85 log.Fatal(err)
86 }
87 }
88}
89
90func getAllEdges() ([]EdgeModel, error) {
91 result := []EdgeModel{}
92 iter := edgeCollection.Find(bson.M{}).Limit(500).Iter()
93 err := iter.All(&result)
94 return result, err
95}
96func saveEdge(c *mgo.Collection, edge EdgeModel) {
97 //first, check if the edge already exists
98 result := EdgeModel{}
99 err := c.Find(bson.M{"txid": edge.Txid}).One(&result)
100 if err != nil {
101 //edge not found, so let's add a new entry
102 err = c.Insert(edge)
103 check(err)
104 } else {
105 err = c.Update(bson.M{"txid": edge.Txid}, &edge)
106 if err != nil {
107 log.Fatal(err)
108 }
109 }
110}