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 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法