duanqiang2977 2017-04-11 09:19
浏览 593
已采纳

如何使用Go更新Mongodb中的数组字段

I want to change stu1 to stu3

import (
    "gopkg.in/mgo.v2"
    "gopkg.in/mgo.v2/bson"
)
type Student struct {
    Name string `bson:"name"`
    Age  string `bson:"age"`
}
type Class struct {
    Id      string    `bson:"_id"`
    Student []Student `bson:"student"`
}

col := mongosession.DB("test").C("class")

stu1 := Student{"jack", "18"}
stu2 := Student{"rose", "16"}
class := Class{Id: "123", Student: []Student{stu1, stu2}}
col.Insert(class)

stu3 := Student{"lisi", "14"}

How do I do the update? Is it like the following

col.Update(bson.M{"_id": "123"},
            bson.M{"$set": bson.M{"student": ??????}})

Any help will be appreciated!

  • 写回答

1条回答 默认 最新

  • dousiyou1058 2017-04-11 09:27
    关注

    You can use the $set operator and the dot notation :

    err := col.Update(
      bson.M{"_id": "123"},
      bson.M{
        "$set": bson.M{
          "student.0": &stu3
        }
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!