Sohail Shaikh February 2016

How to insert multiple values of nested struct in mongodb with go

I am trying to insert multiple values with nested struct in mongodb with golang ... Like this

{  "_id" : ObjectId("56b879528d04effa4ae2de2c"), 
   "task_content" : "Some text",
   "priority" : "2", 
   "deadline" : { 
      "start_time" : ISODate("2009-04-04T00:00:00Z"), 
      "end_time" : ISODate("2009-05-04T00:00:00Z") 
   },
   "users" : {
      "u_status" : "Completed",
      "u_name" : john_smith,
      "u_status" : "Completed",
      "u_name" : harry_potter
   },
 }

Is this possible to do in mongo. i.e. there are same name of keys but the values are different.. Here is Sample code which i tried

type deadLine struct {
    Start_time  time.Time `bson:"start_time"`
    End_time    time.Time `bson:"end_time"`
  }
  type users struct {
    Status  string `bson:"u_status"`
    User_name  string `bson:"u_name"`
  }
  type taskData struct {
    Id bson.ObjectId  `bson:"_id"`
    Task_content string  `bson:"task_content"`
    Priority string  `bson:"priority"`
    deadLine
    users     []users

  }

func TaskToDo(w http.ResponseWriter, r *http.Request) {
    var doc taskData
    retMap := make(map[string]map[string]string)
    retMap["user"]["1"] = "john_smith"
    retMap["user"]["2"] = "harry_potter"

    stime, _ := time.Parse("2006/01/02","2009-04-04")
    etime, _ := time.Parse("2006/01/02","2009-05-04")


    doc = taskData{Id: bson.NewObjectId(),
      Task_content:"Some text", Priority:"2",
      deadLine:deadLine{
        Start_time:stime,
        End_time:etime,
      }}

    for i := 1; i <= len(retMap["user"]);i++ {
      doc.users = append(doc.users, users{
        User_name : retMap["user"][strconv.Itoa(i)],
        Status : "Completed",

      })
    }
    fmt.Println(doc)
    err := collection.Insert(doc)
    if err != nil {
      fmt.Printf("Can't insert document: %v\n", err)
      fmt.Fprintf(w,"%s","Can't insert document:%v\n", err)
      os.Exit(1)
      }else{
        fmt.Println("Task Inse        

Answers


David Budworth February 2016

You need to export your sub structs to make this work.

Like this:

type deadLine struct {
    Start_time  time.Time `bson:"start_time"`
    End_time    time.Time `bson:"end_time"`
}
type users struct {
    Status  string `bson:"u_status"`
    User_name  string `bson:"u_name"`
}
type taskData struct {
    Id bson.ObjectId  `bson:"_id"`
    Task_content string  `bson:"task_content"`
    Priority string  `bson:"priority"`
    DeadLine deadline `bson:"deadline"`
    Users     []users `bson:"users"`
}

Post Status

Asked in February 2016
Viewed 3,231 times
Voted 4
Answered 1 times

Search




Leave an answer