简体   繁体   English

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

[英]How would I go about inserting a subdocument in Mongodb in Golang / mgo?

Say for example I had the following struct: 比如说我有以下结构:

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

How would I go about adding a new category? 我将如何添加新类别?

Sorted it using: 使用以下内容对其进行了排序:

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

Update the Article struct as : Article结构更新为:

type Article struct {
   ArticleId  string      `bson:"_id"`
   Title      string      `form"title" json:"title,omitempty"`
   Categories []Category  `json:"category,omitempty"`
}

Your Query accordingly: 您的查询相应地:

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)

It would be great if you can share your Category struct and include an field _id in your Article struct. 如果您可以共享您的Category结构,并在Article结构中包含一个字段_id ,那就太好了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 golang mongodb(mgo)未插入文档 - golang mongodb (mgo) is not inserting docs Go中的MongoDB(golang)与mgo:如何使用逻辑运算符进行查询? - MongoDB in Go (golang) with mgo: how to use logical operators to query? Golang/mgo:如何在 mongodb 中存储日期(不是 ISODate)? - Golang/mgo : How can I store Date (not ISODate) in mongodb? MongoDB in Go (golang) with mgo:如何更新记录,确定更新是否成功并在单个原子操作中获取数据? - MongoDB in Go (golang) with mgo: How do I update a record, find out if update was successful and get the data in a single atomic operation? 使用golang和mgo,如何在MongoDB中搜索一系列值? - Using golang and mgo, how do I search for a range of values in MongoDB? 如何使用golang和mgo库在mongodb中创建文本索引? - How do I create a text index in mongodb with golang and the mgo library? 如何使用 mgo 和 Go 查询具有日期范围的 MongoDB? - How can I query MongoDB with date range using mgo and Go? 如何使用Go和mgo使用mongodb投影? - How can I use mongodb projections with Go and mgo? 我将如何将MongoDb集合附加到Java视图 - How would i go about to attache a MongoDb Collection to a Java View go 如何使用 ZCCADCDEDB567ABAE643E15DCF0974E503Z 有效地查询 MongoDB? - How would I go about querying MongoDB efficiently using Mongoose?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM