【发布时间】:2018-01-24 21:26:06
【问题描述】:
我有一个游戏分析REST API,它存储玩家的平均表现统计数据。当新的统计数据到来时,我想通过将新的 delta 合并到现有文档中来更新 Mongodb 中现有的游戏记录。我也在存储过去的分析数据。因此,我可以返回自游戏上次更新以来玩家的统计数据正在减少或增加等数据。
问题是:当我想用 mgo 将我的新游戏数据插入到 Mongodb 中时,它会覆盖所有玩家的统计数据数组。实际上,这是意料之中的。如果我可以修改 mgo 尝试将其插入到 Mongodb 中的文档,我知道如何解决它。
问题:如何自定义 mgo upsert 行为?这样我就可以在Player.Stats 前面添加一个$push 运算符,以防止Mongodb 擦除文档中的stats 数组。
我真正的问题:我将使用哪个 Mongo 命令并不重要。我会以某种方式解决的。我真正想知道的是:如何在 upsert 之前自定义 mgo 的行为?
一些解决方案:我自己之前尝试过一些解决方案。比如,将Game struct 编码/解码成bson.M 来定制它。但是,我发现它既麻烦又麻烦。如果没有其他办法,我会使用它。
块:我不想用bson.M 手写所有结构字段,只是在一个字段上使用$push 运算符。因为有几十个字段,所以很容易出错,并且会增加我的代码复杂度。
示例:
// Assume that, this is an existing game in Mongodb:
existingGame := Game{
ID: 1,
Name: "Existing game",
// The game has just one player
Players: []Player{
// The player has some stats. The newest one is 2.0.
{1, "foo", []{3.5, 2.0}},
}
}
// This is a new request coming to my API
// I want to upsert this into the existing Game
newGame := Game{
ID: 1,
Players: []Player{
// As expectedly, this will reset player foo's stats to 5.0
//
// After upserting, I want it to be as:
//
// []{3.5, 2.0, 5.0}
//
// in Mongodb
{1, "foo", []{5.0}},
}
}
// Example 2:
// If new Game request like this:
newGame := Game{ID: 1, Players: []Player{{1, "foo", []{5.0},{1, "bar", []{6.7}}}}
// I'm expecting this result:
Game{ID: 1, Players: []Player{{1, "foo", []{3.5, 2.0, 5.0},{1, "bar", []{6.7}}}}
func (db *Store) Merge(newGame *Game) error {
sess := db.session.Copy()
defer sess.Close()
col := sess.DB("foo").C("games")
// I want to modify newGame here to add a $push operator
// into a new `bson.M` or `bson.D` to make mgo to upsert
// my new delta without resetting the player stats
_, err := col.UpsertId(newGame.ID, newGame)
return err
}
type Game struct {
ID int `bson:"_id"`
Name string
Players []Player `bson:",omitempty"`
// ...I omitted other details for simplicity here...
}
type Player struct {
// This connects the player to the game
GameID int `bson:"game_id"`
Name string
// I want to keep the previous values of stats
// So, that's why I'm using an array here
Stats []float64
// ...
}
我在控制台中尝试了这个 Mongodb 命令来更新特定游戏的玩家:
db.competitions.update({
_id: 1,
"players.game_id": 1
}, {
$push: {
"players.$.stats": 3
}
}, {
upsert: true
})
【问题讨论】:
-
当新游戏是
Game{ID: 1, Players: []Player{{"foo", []{5.0},{"bar", []{6.7}}}}时,你期望的结果是什么? -
我是这么认为的 =( upsert 不适用于子文档。请参阅stackoverflow.com/questions/23470658/…
-
您可以将您使用过的查询添加到问题中吗?我非常好奇,因为您正在推动子子文档。
-
感谢您的更新。只是为了确认我们在同一页面上,简单的 upsert 查询会找到一个 id 为 1 的游戏,并使用 player.game_id = 1 更新 first 玩家,如果存在则 fails是没有这样的玩家,或者没有这样的游戏。您对这种行为感到满意并且只想在 go 中编写代码吗? upsert 部分在这种情况下没有意义,所以我想确认一下。
-
嗯,不确定是否得到最后一条评论。我很欣赏你将问题减少到 mvce,但我认为你剥离了太多。明确一点:在当前版本中,新玩家不能通过单一的统计数据添加到游戏中。您也不能通过单个查询更新游戏中的多个现有玩家。