【问题标题】:Unmarshal from array of MongoDB subdocuments with mgo Golang使用 mgo Golang 从 MongoDB 子文档数组中解组
【发布时间】:2019-05-09 15:58:46
【问题描述】:

我试图弄清楚如何从数组中获取单个子文档并将其解组到结构中。

我的 mongo 文档如下所示:

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

我有一个如下所示的播放器结构:

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

从 mongo 命令行我可以做一个

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

返回

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

但是我很难弄清楚如何在 Go 中实现相同的功能,以便从查询结果中获得填充的玩家结构。我一直在玩弄下面代码的不同配置,但它总是导致一个空结构。我在这里错过了什么?

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

我正在运行最新的 MongoDB 版本,并且正在使用用于 Go 的 mgo.v2 驱动程序。

【问题讨论】:

    标签: mongodb go mgo


    【解决方案1】:

    这是因为你不俘虏一个玩家,你俘虏了玩家。 就像 mongo 命令的响应一样:

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

    听起来你可以抽象为game

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

    您的电话将转至&game

    var game Game
    collection.Find(bson.M{"...").One(&game)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-07
      • 1970-01-01
      • 2018-07-28
      • 2014-09-14
      • 2018-04-16
      • 1970-01-01
      • 1970-01-01
      • 2013-07-23
      相关资源
      最近更新 更多