How to update array's field in Mongodb with Go

huangapple go评论100阅读模式
英文:

How to update array's field in Mongodb with Go

问题

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

任何帮助将不胜感激!

英文:

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

得分: 0

你可以使用$set操作符和点符号表示法

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

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
    }
})

huangapple
  • 本文由 发表于 2017年4月11日 17:19:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/43341732.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定