[英]How would I go about inserting a subdocument in Mongodb in Golang / mgo?
比如说我有以下结构:
type Article struct {
Title string `form"title" json:"title"`
Categories []*Category
}
我将如何添加新类别?
使用以下内容对其进行了排序:
change := mgo.Change{
Update: bson.M{"$push": bson.M{"categories": cat}},
}
_, err := repo.collection.FindId(bson.ObjectIdHex(article)).Apply(change, nil)
if err != nil {
panic(err)
}
将Article结构更新为:
type Article struct {
ArticleId string `bson:"_id"`
Title string `form"title" json:"title,omitempty"`
Categories []Category `json:"category,omitempty"`
}
您的查询相应地:
data := model.Category{
CategoryId : "yourText",
Product : "productName,
...
}
selector := bson.M{"_id": "provideTheTitle"}
changes := bson.M{"$push": bson.M{"category": bson.M{"$each": []model.Category{data}}}}
err = c.Update(selector, changes)
如果您可以共享您的Category结构,并在Article结构中包含一个字段_id ,那就太好了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.