dpmwy80068 2018-11-01 13:53
浏览 350
已采纳

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

  • 写回答

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
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 matlab appdesigner私有函数嵌套整合
  • ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题