如何使用go在mongodb中插入嵌套结构的多个值

时间:2016-02-08 11:55:37

标签: mongodb go struct

我正在尝试使用golang在mongodb中使用嵌套结构插入多个值...就像这样

{  "_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
   },
 }

这可以在mongo中完成。即,键的名称相同,但值不同。这是我尝试的示例代码

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 Inserted Successfully ... ")
      }
}

忽略示例代码中的一些基本错误。请帮助我提前谢谢

1 个答案:

答案 0 :(得分:0)

您需要导出子结构才能使其正常工作。

像这样:

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"`
}