使用MongoDB在Golang中检查对象数组中的重复项
I need to find duplicate entries of a specific value in an array of objects in a Mongo database. My structure looks something 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"`
}
If a new player is joining the game, I want to check to make sure their username is not taken. I used this method for checking for duplicate game codes (if count
is greater than 1, I know there's a game that exists):
count, err := collection.Find(bson.M{"gamecode": entry.GameCode}).Limit(1).Count()
Which works well, but obviously won't work to check the username
value of an object in the array of players. I am thinking I would have to do something along the lines of checking the size of the array and iterating through each option to find a duplicate, but I haven't had any sort of success.
EDIT
I am running the latest version of MongoDB and am using the mgo.v2 driver for go. The flow of what I am trying to achieve looks something like this:
Player Y wants to join game X. Game X can only have a single instance of a 'username', but that same username can be present in other games.
我需要在Mongo数据库中的对象数组中查找特定值的重复条目。 我的结构如下所示: p>
type gameTemplate结构{
ID bson.ObjectId`bson:“ _ id” json:“ id”`
GameCode字符串`bson:“ gamecode “ json:” gamecode“`
Players [] player`bson:” players“ json:” players“`
}
type player struct {
PlayerID bson.ObjectId`bson:” playerid“ json:” playerid“ `
用户名字符串`bson:“用户名” json:“用户名”`
}
code> pre>
如果有新玩家加入游戏,我想检查 确保未使用其用户名。 我使用这种方法检查重复的游戏代码(如果 count code>大于1,我知道存在一个游戏): p>
count, err:= collection.Find(bson.M {“ gamecode”:entry.GameCode})。Limit(1).Count()
code> pre>
效果很好, 但显然无法检查玩家数组中对象的 username code>值。 我想我将不得不执行以下操作:检查数组的大小并遍历每个选项以查找重复项,但是我没有任何成功。 p>
编辑 strong> p>
我正在运行最新版本的MongoDB,并且正在使用mgo.v2驱动程序。 我要实现的目标流程看起来像这样: p>
玩家Y想要加入游戏X。游戏X只能有一个“用户名”实例 ',但其他游戏中也可以使用相同的用户名。 p>
blockquote>
div>
You can use $elemMatch
collection.Find(bson.M{"gamecode": entry.GameCode},bson.M{"players": bson.M{"$elemMatch": bson.M{"playerid": playerid}}}).Limit(1).Count()