如何更新数组';Mongodb中的s场与Go
我想将如何更新数组';Mongodb中的s场与Go,mongodb,go,mongodb-query,bson,Mongodb,Go,Mongodb Query,Bson,我想将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"
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": ??????}})
任何帮助都将不胜感激 您可以使用
$set
操作符和:
谢谢它起作用了。如果我不知道stu1是数组中的0字段,我只知道名称是“jack”,那么如何编写更新代码呢?
err:=col.update(bson.M{u id:“123”,“student.name:“jack”},bson.M{set:“bson.M{”student.$:&stu3})
这可以工作。
err := col.Update(
bson.M{"_id": "123"},
bson.M{
"$set": bson.M{
"student.0": &stu3
}
})