Search code examples
mongodbgomgo

Get values from array of child objects in Golang with MongoDB


I am using the mgo.v2 driver with the latest version of MongoDB installed. My document structure is defined like this:

type gameTemplate struct {
ID       bson.ObjectId `bson:"_id" json:"id"`
GameCode string        `bson:"gamecode" json:"gamecode"`
Players  []player      `bson:"players" json:"players"`
}

type player struct {
PlayerID bson.ObjectId `bson:"playerid" json:"playerid"`
Username string        `bson:"username" json:"username"`
Level    int           `bson:"level" json:"level"`
}

How would I go about getting a list of usernames in a particular game (Defined by gamecode)?

Is there a way to get the size of the array and iterate through the elements, or is there a preferred method?


Solution

  • you could get all player with specific game code like this:

    players := []gameTemplate{}
    err = session.DB(DBname).C(Colloctionname).Find(bson.M{}).All(&players) 
    

    as you defined each players has username and size of players slice is the number of username which has specific game code.


    ps:
    be careful and change DBname and Colloctionname whit your Database and collection name and use session of your databse connection be