【问题标题】:Customize mgo upsert operation自定义 mgo upsert 操作
【发布时间】: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,但我认为你剥离了太多。明确一点:在当前版本中,新玩家不能通过单一的统计数据添加到游戏中。您也不能通过单个查询更新游戏中的多个现有玩家。

标签: mongodb go mgo


【解决方案1】:

要回答“我的真正问题:如何在 upsert 之前自定义 mgo 的行为?” - 您可以通过为模型定义 bson Getter 来自定义 bson 编组。

为了说明它的工作原理,让我们简化模型以避免嵌套文档:

type Game struct {
    ID int `bson:"_id"`
    Name string
    Stats [] float64
}

newGame 如下:

newGame := Game{
    ID: 1,
    Name: "foo",
    Stats: []{5.0}
}

更新 col.UpsertId(newGame.ID, newGame) 默认将 newGame 编组为 JSON,生成如下 mongo 查询:

update({_id:1}, {name: "foo", stats: [5]}, {upsert: true});

要使用$set、$push 等,你可以定义一个自定义的bson getter。例如

func (g Game) GetBSON() (interface{}, error) {
    return bson.M{
        "$set": bson.M{"name": g.Name}, 
        "$push": bson.M{"stats": bson.M{"$each": g.Stats}},
    }, nil
}

所以更新col.UpsertId(newGame.ID, newGame)会产生一个mongodb查询

update({_id:1}, {$set: {name: "foo"}, $push: {stats: {$each: [5]}}}, {upsert: true});

为了清楚起见 - 自定义封送拆收器将用于所有 mgo 查询,因此您可能不想将其直接定义到模型,而是定义为仅用于 upsert 操作的派生:

type UpdatedGame struct {
    Game
}

func (g UpdatedGame) GetBSON() (interface{}, error) {
    return bson.M{....}
}

.....

newGame := Game{
    ID: 1,
    Name: "foo",
    Stats: []{5.0}
}

col.UpsertId(newGame.ID, UpdatedGame{newGame})

【讨论】:

  • 告诉你 =(,无论如何我已经更新了答案,以明确“定制”是如何工作的。
  • 我没有得到这部分。不确定从哪里弹出复杂性和错误,但如果您想以编程方式进行,只需编组嵌入式游戏并将其解组为 bson.M 类型。然后,您可以随心所欲地操作地图。请注意后果。使用硬编码的 bson,您可以捕获编译时的所有错误。将其转移到运行时实际上会增加代码复杂性并且必须在运行时捕获错误。
猜你喜欢
  • 2018-11-06
  • 1970-01-01
  • 2014-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-09
  • 1970-01-01
相关资源
最近更新 更多