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

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

How to update array inside Go model for Mongo

问题

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

type LevelModel struct {
	Index int `json:"index" bson:"index"`
	Time  int64 `json:"time" bson:"time"`
}

type PlayerModel struct {
	ID    bson.ObjectId `json:"_id,omitempty" bson:"_id,omitempty"`
	Score int64         `json:"score" bson:"score"`
	Level []LevelModel  `json:"level" bson:"level"`
}

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

英文:

I have Player model in Go for Mongo and model Level

type LevelModel struct {
	Index 			int 				`json: "index" bson: "index"`
	Time 			int64 				`json: "time" bson: "time"`
}


type PlayerModel struct {
	ID 				bson.ObjectId 		`json: "_id, omitempty" bson: "_id, omitempty"`
	Score 			int64 				`json: "score" bson: "score"`
	Level 			[]LevelModel	`json: "level" bson: "level"`
}

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文档),可以应用一个简单的算法,例如:

func (p *PlayerModel) updateLevel(idx int, time int64) {
    for i := range p.Level {
        lm := &(p.Level[i])
        if lm.Index == idx {
            if time < lm.Time {
                lm.Time = time
            }
            return
        }
    }
    p.Level = append(p.Level, LevelModel{idx, time})
}

在此处查看示例: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:

func (p *PlayerModel) updateLevel(idx int, time int64) {
    for i := range p.Level {
	    lm := &amp;(p.Level[i])
    	if lm.Index == idx {
		    if time &lt; lm.Time {
			    lm.Time = time
		    }
		    return
	    }
    }
    p.Level = append(p.Level, LevelModel{idx, time})
}

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:

确定