douping7975 2018-12-07 21:36
浏览 106
已采纳

使用mgo Golang从MongoDB子文档数组中解组

I am trying to figure out how to get a single subdocument from an array and unmarshal it into a struct.

My mongo document looks like this:

{ 
    "_id" : ObjectId("abc123"), 
    "gamecode" : "abc123"
    "players" : [ 
        { 
            "playerid" : ObjectId("abc123"), 
            "username" : "test", 
        },
        { 
            "playerid" : ObjectId("abc456"), 
            "username" : "test2"
        }]
 }

And I have a player struct that looks like this:

type Player struct {
    PlayerID bson.ObjectId `bson:"playerid" json:"playerid"`
    Username string        `bson:"username" json:"username"`
}

From the mongo command line I can do a

db.games.find(({"players.playerid": ObjectId('abc123')}, {"_id": 0, "players.$":1})

Which returns

{"players" : [{ "playerid" : ObjectId("abc123"), "username" : "test"}]}

But I am having a hard time figuring out how to implement this same functionality in Go so that I have a populated player struct from the result of the query. I have been playing around with different configurations of the code below, but it always results in an empty struct. What am I missing here?

player := Player{}
collection.Find(bson.M{"players.playerid": bson.ObjectIdHex(pid)}).Select(bson.M{"_id": 0, "players.$": 1}).One(&player)

I am running the latest MongoDB version and am using the mgo.v2 driver for Go.

  • 写回答

1条回答 默认 最新

  • dongqing5925 2018-12-07 22:56
    关注

    It's because you don't capture a single player, you capture players. like in the response from the mongo command:

    {"players" : [{ "playerid" : ObjectId("abc123"), "username" : "test"}]}
    

    Sounds like you can you an abstraction for a game

    type Game struct {
        Players []Player `bson:"players"`
    }
    

    And your call would be into &game

    var game Game
    collection.Find(bson.M{"...").One(&game)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵