自定义 mgo upsert 操作

Customize mgo upsert operation

我有一个游戏分析表 API,它存储玩家的平均表现统计数据。当新的统计数据到达时,我想通过将新的增量合并到现有文档来更新 Mongodb 中现有的游戏记录。我也在存储过去的分析数据。因此,我可以 return 数据,例如自游戏上次更新以来玩家的统计数据正在减少或增加。

问题是: 当我想用 mgo 将我的新游戏数据更新到 Mongodb 时,它会覆盖玩家的所有统计数据数组。实际上,这是意料之中的。我知道如何修复它,如果我可以修改我的文档,mgo 试图插入到 Mongodb.

问题:如何自定义 mgo upsert 行为?这样我就可以在 Player.Stats 前面添加一个 $push 运算符,以防止 Mongodb 擦除文档中的 stats 数组。

我的真正问题: 我要使用哪个 Mongo 命令并不重要。我会想办法的。我真正想知道的是:如何在 upsert 之前自定义 mgo 的行为?

一些解决方案:我以前自己尝试过一些解决方案。比如,encoding/decoding Game 结构化为 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
})

回答“我的真正问题:如何在更新插入之前自定义 mgo 的行为?”- 您可以通过将 bson Getter 定义为模型。

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

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

新游戏如下:

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

要明确 crystal - 自定义封送拆收器将用于所有 mgo 查询,因此您可能不想将其直接定义到模型,而是定义到其派生以用于更新插入操作仅:

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