dpmwy80068
2018-11-01 13:53
浏览 253

使用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?

图片转代码服务由CSDN问答提供 功能建议

我正在使用安装了最新版本MongoDB的mgo.v2驱动程序。 我的文档结构定义如下:

  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“`
} 
   
 
 <  p>如何获取特定游戏中的用户名列表(由 gamecode 定义)?   
 
 

是否有一种获取数组大小并遍历元素的方法,还是有一种首选的方法?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • drwo32555 2018-11-02 20:23
    已采纳

    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
    打赏 评论

相关推荐 更多相似问题