// 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.
{"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 3.5
//
// After upserting, I want it to be as:
//
// []{3.5, 2.0, 5.0}
//
// in Mongodb
{"foo", []{5.0}},
}
}
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 {
Name string
// I want to keep the previous values of stats
// So, that's why I'm using an array here
Stats []float64
// ...
}