使用MongoDB从Golang中的子对象数组获取值
问题描述:
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?
我正在使用安装了最新版本MongoDB的mgo.v2驱动程序。 我的文档结构定义如下: p>
type gameTemplate结构{
ID bson.ObjectId`bson:“ _ id” json:“ id”`
GameCode字符串`bson:“ gamecode“ json:” gamecode“`
Players [] player`bson:” players“ json:” players“`
}
type player struct {
PlayerID bson.ObjectId`bson:” playerid“ json:” playerid “`
用户名字符串`bson:”用户名“ json:”用户名“`
Level int`bson:” level“ json:” level“`
}
code> pre>
如何获取特定游戏中的用户名列表(由 gamecode code>定义)? p>
是否有一种获取数组大小并遍历元素的方法,还是有一种首选的方法? p>
div>
答
ps:
be careful and change DBname and Colloctionname whit your Database and collection name and use session of your databse connection be
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