-2

I am trying to set up a database for my simple project. Since in MongoDB you can save any JSON file I was wondering is there an easy solution to directly save a struct to MongoDB as a json file?

Stefan Drissen
  • 3,266
  • 1
  • 13
  • 21
Bat
  • 771
  • 11
  • 29
  • 1
    yes you can save struct directly to mongodb – novalagung Mar 03 '20 at 07:23
  • 1
    What have you tried? Include your code. What problems did you encounter? Be specific. – Jonathan Hall Mar 03 '20 at 07:26
  • 1
    Yes, you can marshal to JSON any struct in golang and then save it to mongoDB. However you should include your code to be more specific in the issue. Example of struct JSON marshal: https://stackoverflow.com/questions/8270816/converting-go-struct-to-json The you can write it to file if there is needed to complete the task: https://gobyexample.com/writing-files – Aleksey Spirin Mar 03 '20 at 07:28
  • It would also be very, very unusual to marshal a struct to JSON and store that in MongoDB. MongoDB documents are in **BSON** format, *not* JSON. – Adrian Mar 03 '20 at 14:44

1 Answers1

2

This is the sample code to store the structure type data in the Mongodb database

To get data as JSON format from mongodb you have json.Marshal() method in

package main

import (
    "context"
    "fmt"
    "log"
    "io/ioutil"

    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
    "go.mongodb.org/mongo-driver/mongo/options"
)

type Person struct {
    ID int `json:"_id"`
    Age  int    `json:"Age"`
    City string `json:"city"`
}

func main() {
    clientOptions := options.Client().ApplyURI("mongodb://127.0.0.1:27017")
    client, err := mongo.Connect(context.TODO(), clientOptions)

    if err != nil {
        log.Fatal(err)
    }

    ctx, _ := context.WithTimeout(context.Background(), 3*time.Second)   
    fmt.Println("Connected to MongoDB!")
    collection := client.Database("db_name").Collection("collection_name")
    byteValues, err := ioutil.ReadFile("docs.json")
    if err != nil {
          fmt.Println("ioutil.ReadFile ERROR:", err)
    } else {
          fmt.Println("ioutil.ReadFile byteValues TYPE:", reflect.TypeOf(byteValues))
          fmt.Println("byteValues:", byteValues, "n")
          fmt.Println("byteValues:", string(byteValues))
    }
    for i := range docs {
           doc := docs[i]
           fmt.Println("ndoc _id:", doc.ID)
           fmt.Println("doc Field Str:", doc.ID)
           result, insertErr := col.InsertOne(ctx, doc)
           if insertErr != nil {
                  fmt.Println("InsertOne ERROR:", insertErr)
           } else {
           fmt.Println("InsertOne() API result:", result)
      }
}
srinu vas
  • 50
  • 6