-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
110 lines (78 loc) · 1.89 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"encoding/csv"
"io"
"os"
"fmt"
"github.com/faerulsalamun/go-csv-mongodb-wilayah-administrasi-indonesia/db"
"log"
"gopkg.in/mgo.v2/bson"
)
type Province struct {
ID bson.ObjectId `json:"_id" bson:"_id,omitempty"`
Name string `json:"name"`
}
type Regency struct {
ID bson.ObjectId `json:"_id" bson:"_id,omitempty"`
ProvinceID bson.ObjectId `json:"province_id" bson:"province_id,omitempty"`
Name string `json:"name"`
}
func main() {
fmt.Println("Start insert data")
con := db.Init()
defer db.CloseSession()
file, err := os.Open("data/provinces.csv")
if err != nil {
fmt.Println("Error:", err)
return
}
defer file.Close()
reader := csv.NewReader(file)
reader.Comma = ','
for {
record, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
fmt.Println("Error:", err)
return
}
var id_province = bson.NewObjectId()
err = con.C("provincies").Insert(&Province{ID: id_province, Name: record[1]})
if err != nil {
log.Fatal(err)
}
// Search regencies
file_regencies, err_regencies := os.Open("data/regencies.csv")
if err_regencies != nil {
fmt.Println("Error:", err)
return
}
defer file_regencies.Close()
reader_regencies := csv.NewReader(file_regencies)
reader_regencies.Comma = ','
var regencies []interface{}
for {
record_regencies, err_regencies := reader_regencies.Read()
if err_regencies == io.EOF {
break
} else if err_regencies != nil {
fmt.Println("Error:", err)
return
}
if record[0] == record_regencies[1] {
regencies = append(regencies, &Regency{
ID: bson.NewObjectId(),
ProvinceID: id_province,
Name: record_regencies[2]})
}
}
bulk := con.C("regencies").Bulk()
bulk.Insert(regencies...)
_, bulkErr := bulk.Run()
if bulkErr != nil {
panic(err)
}
}
fmt.Println("Done insert data")
}