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

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

报告相同问题?

悬赏问题

  • ¥15 带序列特征的多输出预测模型
  • ¥15 VB.NET读取电脑主板序列号
  • ¥15 Python 如何安装 distutils模块
  • ¥15 关于#网络#的问题:网络是从楼上引一根网线下来,接了2台傻瓜交换机,也更换了ip还是不行
  • ¥15 资源泄露软件闪退怎么解决?
  • ¥15 CCF-CSP 2023 第三题 解压缩(50%)
  • ¥30 comfyui openpose报错
  • ¥20 Wpf Datarid单元格闪烁效果的实现
  • ¥15 图像分割、图像边缘提取
  • ¥15 sqlserver执行存储过程报错