How to insert multiple values of nested struct in mongodb with go -
i trying insert multiple values nested struct in mongodb golang ...
{ "_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 possible in mongo. i.e. there same name of keys values different.. here sample code 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, }} := 1; <= 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 ... ") } }
ignore basic mistakes in sample code. kindly me in advance
you need export sub structs make 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"` }
Comments
Post a Comment