【问题标题】:How to update array's field in Mongodb with Go如何使用 Go 更新 Mongodb 中的数组字段
【发布时间】:2017-04-11 17:35:44
【问题描述】:

我想把stu1改成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"}

如何进行更新?是不是像下面这样

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

任何帮助将不胜感激!

【问题讨论】:

    标签: mongodb go mongodb-query bson


    【解决方案1】:

    您可以使用$set 运算符和dot notation

    err := col.Update(
      bson.M{"_id": "123"},
      bson.M{
        "$set": bson.M{
          "student.0": &stu3
        }
    })
    

    【讨论】:

    • 谢谢!有用。如果我不知道stu1是数组中的0字段,我只知道名字是“jack”,那更新代码怎么写?
    • err := col.Update(bson.M{"_id": "123", "student.name": "jack"}, bson.M{"$set": bson.M{"student.$": &stu3}}) 这可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 1970-01-01
    • 2020-06-10
    • 2021-07-20
    • 1970-01-01
    相关资源
    最近更新 更多