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
        }
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择
  • ¥15 这款软件是什么?需要能满足我的需求
  • ¥15 SpringSecurityOauth2登陆前后request不一致
  • ¥15 禅道二次开发编辑版本,上传不了发行包