所以我想对下面的结构进行多级推送:
type Inspector_Pool struct{
Unique_Id string `json:"unique_id" form:"unique_id" query:"unique_id"`
Email string `json:"email" form:"email" query:"email"`
Branch []string `json:"branch" query:"branch"`
Date []Date `json:"date" query:"date"`
}
type Date struct {
Event_Timestamp string `json:"event_timestamp" query:"event_timestamp"`
Event []Event `json:"event" query:"event"`
}
type Event struct {
Event_Name string `json:"event_name" form:"event_name" query:"event_name"`
Event_Id string `json:"event_id" form:"event_id" query:"event_id"`
Status string `json:"status" query:"status"`
}
所以我想要的是在Event数组中推送数据,所以我必须实现以下代码:
//push a new node in date array
query := bson.M{"branch":"400612", "unique_id":c.Unique_Id}
update := bson.M{"$push": bson.M{"date": bson.M{"event_timestamp": t, "event": []models.Event{
{
Event:models.INSPECTION,
Event_Id:"123456789",
Status:models.PENDING,
},
}}}}
err = look_up.Update(query, update)
if err != nil {
panic(err)
}
//push the data in the nested event
pushQuery := bson.M{"date.event": bson.M{"event": []models.Event{
{
Event_Name:models.INSPECTION,
Event_Id:"4984984198",
Status:models.PENDING,
},
}}}
err = look_up.Update(bson.M{"unique_id": "2549090", "date.event_timestamp":"08-05-2017"}, bson.M{"$push": pushQuery})
if err != nil {
//panic(err)
fmt.Print("error_2",err)
}
答案 0 :(得分:1)
您可以使用$ positional运算符进行更新。这基本上标识了要更新的数组中的元素,而没有明确指定数组中元素的位置。
改变你的第二个推送声明如下:
pushQuery := bson.M{"date.$.event": Event{
Event_Name:"foobar",
Event_Id:"4984984198",
}}
err = collection.Update(bson.M{"unique_id":"2549090",
"date.event_timestamp":"08-05-2017"},
bson.M{"$push": pushQuery})
以上将推动活动' foobar'进入相同的日期数组匹配event_timestamp' 08-05-2017'即
{"_id": ObjectId("5909287934cb838fe8f89b6e"),
"unique_id": "2549090",
"date": [
{
"event_timestamp": "08-05-2017",
"event": [
{
"event_name": "baz",
"event_id": "123456789"
},
{
"event_name": "foobar",
"event_id": "4984984198"
}
]
}
]}
通常拥有一个数组数组,这使得稍后查询或提取数据变得困难/复杂。根据您的应用程序的使用案例,我还建议您重新考虑document Data Model。