[英]Unmarshal from array of MongoDB subdocuments with mgo Golang
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: 我的mongo文件看起来像这样:
{
"_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 从mongo命令行,我可以执行
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. 但是我很难弄清楚如何在Go中实现相同的功能,以便从查询结果中获得填充的播放器结构。 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. 我正在运行最新的MongoDB版本,并且正在使用Go的mgo.v2驱动程序。
It's because you don't capture a single player, you capture players. 这是因为您没有捕获单个玩家,而是捕获了玩家。 like in the response from the mongo command: 就像在mongo命令的响应中一样:
{"players" : [{ "playerid" : ObjectId("abc123"), "username" : "test"}]}
Sounds like you can you an abstraction for a game
听起来您可以将game
抽象化
type Game struct {
Players []Player `bson:"players"`
}
And your call would be into &game
您的电话将会进入&game
var game Game
collection.Find(bson.M{"...").One(&game)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.