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

报告相同问题?

悬赏问题

  • ¥35 平滑拟合曲线该如何生成
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站