2017-04-11 58 views
0

我想改变stu1stu3如何更新阵列的场MongoDB中与围棋

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": ??????}}) 

任何帮助将不胜感激!

回答

0

可以使用$set运营商和dot notation

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

谢谢!有用。如果我不知道stu1是数组中的0字段,我只知道名称是“jack”,那么如何编写更新代码呢? – jiahuat

+0

'err:= col.Update(bson.M {“_id”:“123”,“student.name”:“jack”}, \t \t bson.M {“$ set”:bson.M {“student 。$“:&stu3}})' \t \t这可以工作。 – jiahuat