我如何在Golang / mgo中插入Mongodb中的子文档?

时间:2015-11-30 19:31:03

标签: mongodb go mgo

比如说我有以下结构:

type Article struct {
    Title string `form"title" json:"title"`
    Categories []*Category 
}

我如何添加新类别?

2 个答案:

答案 0 :(得分:0)

使用以下方式对其进行排序:

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)
}

答案 1 :(得分:0)

文章结构更新为:

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 ,那就太好了。

相关问题