RamelHenderson
RamelHenderson

Reputation: 2361

Using Go - How to Export MongoDB docs using the official mongoexport package?

I tried this earlier today and it worked. Any better idea? I have to incorporate a way to get keys even from docs that don't have the same fields which is tricky. Thanks in advance!

//get the all keys from the first document
var keys []string
for key, _ := range docs[0].Map() {
   keys = append(keys, key)
}

//Create the csv file for the upcoming io.writer
export, err := os.Create("export.csv")
if err != nil {
   log.Println(err.Error())
   panic(err)
}
defer export.Close()

//Initialize the mongoexport csv export writer.
csvExport := mongoexport.NewCSVExportOutput(keys, false, export)
defer csvExport.Flush()

//Write the header to the export
err = csvExport.WriteHeader()
if err != nil {
   log.Println(err.Error())
   panic(err)
}

//Iterate through each doc and write to the export.
for _, doc := range docs {
   err := csvExport.ExportDocument(*doc)
   if err != nil {
      log.Println(err.Error())
      panic(err)
   }
}

Upvotes: 1

Views: 383

Answers (0)

Related Questions