如何在Go模型中更新Mongo中的数组?

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

How to update array inside Go model for Mongo

问题

我有一个Go语言中的Player模型和Level模型。

  1. type LevelModel struct {
  2. Index int `json:"index" bson:"index"`
  3. Time int64 `json:"time" bson:"time"`
  4. }
  5. type PlayerModel struct {
  6. ID bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
  7. Score int64 `json:"score" bson:"score"`
  8. Level []LevelModel `json:"level" bson:"level"`
  9. }

如果我有PlayerModel的实例(player指针),如何更新其中的Level?Player可以玩新的(尚未玩过的)关卡(然后插入),或者已经玩过(如果时间低于已达到的关卡时间,则更新)。

英文:

I have Player model in Go for Mongo and model Level

  1. type LevelModel struct {
  2. Index int `json: "index" bson: "index"`
  3. Time int64 `json: "time" bson: "time"`
  4. }
  5. type PlayerModel struct {
  6. ID bson.ObjectId `json: "_id, omitempty" bson: "_id, omitempty"`
  7. Score int64 `json: "score" bson: "score"`
  8. Level []LevelModel `json: "level" bson: "level"`
  9. }

How to update Level from PlayerModel if I have instance of PlayerModel ( player pointer ) ?
Player can play new ( not yet played ) level ( then insert ) or already played ( just update if time is lower then already achieved for that level ).

答案1

得分: 3

如果只是更新内存中的数据结构(无论它是否映射到MongoDB文档),可以应用一个简单的算法,例如:

  1. func (p *PlayerModel) updateLevel(idx int, time int64) {
  2. for i := range p.Level {
  3. lm := &(p.Level[i])
  4. if lm.Index == idx {
  5. if time < lm.Time {
  6. lm.Time = time
  7. }
  8. return
  9. }
  10. }
  11. p.Level = append(p.Level, LevelModel{idx, time})
  12. }

在此处查看示例:https://play.golang.org/p/C8SGqkgZ99

英文:

If this is just about updating a data structure in memory (whether it maps a MongoDB document or not), a naive algorithm can be applied, such as:

  1. func (p *PlayerModel) updateLevel(idx int, time int64) {
  2. for i := range p.Level {
  3. lm := &amp;(p.Level[i])
  4. if lm.Index == idx {
  5. if time &lt; lm.Time {
  6. lm.Time = time
  7. }
  8. return
  9. }
  10. }
  11. p.Level = append(p.Level, LevelModel{idx, time})
  12. }

See an example at: https://play.golang.org/p/C8SGqkgZ99

huangapple
  • 本文由 发表于 2015年10月31日 20:17:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/33451473.html
匿名

发表评论

匿名网友

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

确定