arnaucube
arnaucube/cellMapVisualizerPublic Self-hosted repository
cellMapVisualizer/mongoOperations.go
mongoOperations.goRaw
 1package main
 2
 3import (
 4	"encoding/json"
 5	"fmt"
 6	"io/ioutil"
 7
 8	mgo "gopkg.in/mgo.v2"
 9)
10
11//MongoConfig stores the configuration of mongodb to connect
12type MongoConfig struct {
13	Ip       string `json:"ip"`
14	Database string `json:"database"`
15}
16
17var mongoConfig MongoConfig
18
19func readMongodbConfig(path string) {
20	file, e := ioutil.ReadFile(path)
21	if e != nil {
22		fmt.Println("error:", e)
23	}
24	content := string(file)
25	json.Unmarshal([]byte(content), &mongoConfig)
26}
27
28func getSession() (*mgo.Session, error) {
29	session, err := mgo.Dial("mongodb://" + mongoConfig.Ip)
30	if err != nil {
31		panic(err)
32	}
33	//defer session.Close()
34
35	// Optional. Switch the session to a monotonic behavior.
36	session.SetMode(mgo.Monotonic, true)
37
38	// Optional. Switch the session to a monotonic behavior.
39	session.SetMode(mgo.Monotonic, true)
40
41	return session, err
42}
43func getCollection(session *mgo.Session, collection string) *mgo.Collection {
44
45	c := session.DB(mongoConfig.Database).C(collection)
46	return c
47}