ansh
ansh

Reputation: 35

How to save user data written in csv file in mongodb in any format?

Suppose there is a csv file is formated as below :-

first file

firstname|lastname|Email| other fields
         |        |     |
         |        |     |
         |        |     |
         |        |     |

Second file:-

email|firstname|lastname|other fields
     |         |        |
     |         |        |
     |         |        |
     |         |        |

third file

lastname|firstname|email|other fields     
        |         |     |
        |         |     |
        |         |     |
        |         |     |

So I want to save these three files in mongodb database separately. In the given below format:

Format is first_name, last_name,email, otherfield

Code I'm using:-

  package main

import (
 "encoding/csv"
 "gopkg.in/mgo.v2"
 "io"
 "log"
 "os"
)

type Mongo struct {
  // Id          int    `json:"_id" bson:"_id"`
  FirstName   string `json:"first_name,omitempty" bson:"first_name,omitempty"`
  LastName    string `json:"last_name,omitempty" bson:"last_name,omitempty"`
  Email       string `json:"email,omitempty" bson:"email,omitempty"`
  PhoneNumber string `json:"phone_number,omitempty" bson:"phone_number,omitempty"`
  Gender      string `json:"gender,omitempty" bson:"gender,omitempty"`
  Address     string `json:"address,omitempty" bson:"address,omitempty"`
  Apartment   string `json:"apartment,omitempty" bson:"apartment,omitempty"`
  Description string `json:"description,omitempty" bson:"description,omitempty"`
 }

func main() {

 session, err := mgo.Dial("localhost")
 if err != nil {
    panic(err)
 }

 defer session.Close()
 session.SetMode(mgo.Monotonic, true)

 c := session.DB("Import_Users").C("users")

 file, err := os.Open("customers.csv")

 if err != nil {
    panic(err)
 }
 defer file.Close()

 reader := csv.NewReader(file)

 for {
    record, err := reader.Read()
    if err == io.EOF {
        break
    } else if err != nil {
        panic(err)
    }

    err = c.Insert(&Mongo{record[0], record[1], record[2], record[3], record[4], record[5], record[6], record[7]})

    if err != nil {
        panic(err)
    }
    log.Printf("%#v", record)
 }
}

The code I'm using is simple to save the data in the mongodb but it will not format the data which I need to save

How can I achieve my goal?

Upvotes: 0

Views: 410

Answers (1)

Cornel Damian
Cornel Damian

Reputation: 733

I think you can use reflection to map each row of the csv over a structure. Something like the json encoding package is doing from a string to a structure. Then that structure can be inserted in mongodb.

Something like this you want? https://play.golang.org/p/hg3K-u8l9mx

You need to more protection on it and you can do a lot of speed improvements on it, but this is something like the Unmarshal from json pkg.

Upvotes: 1

Related Questions