使用 MongoDB 检查 Golang 中对象数组中的重复项
Check for duplicates in an array of objects in Golang with MongoDB
我需要在 Mongo 数据库的对象数组中查找特定值的重复条目。我的结构看起来像这样:
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"`
}
如果有新玩家加入游戏,我想检查以确保他们的用户名没有被占用。我用这个方法来检查重复的游戏代码(如果 count
大于 1,我知道有一个游戏存在):
count, err := collection.Find(bson.M{"gamecode": entry.GameCode}).Limit(1).Count()
效果很好,但显然无法检查玩家数组中对象的 username
值。我想我必须按照检查数组的大小和遍历每个选项以找到重复项的方式做一些事情,但我没有取得任何成功。
编辑
我是 运行 最新版本的 MongoDB 并且正在使用 mgo.v2 驱动程序。我想要实现的流程看起来像这样:
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.
您可以使用$elemMatch
collection.Find(bson.M{"gamecode": entry.GameCode},bson.M{"players": bson.M{"$elemMatch": bson.M{"playerid": playerid}}}).Limit(1).Count()
我需要在 Mongo 数据库的对象数组中查找特定值的重复条目。我的结构看起来像这样:
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"`
}
如果有新玩家加入游戏,我想检查以确保他们的用户名没有被占用。我用这个方法来检查重复的游戏代码(如果 count
大于 1,我知道有一个游戏存在):
count, err := collection.Find(bson.M{"gamecode": entry.GameCode}).Limit(1).Count()
效果很好,但显然无法检查玩家数组中对象的 username
值。我想我必须按照检查数组的大小和遍历每个选项以找到重复项的方式做一些事情,但我没有取得任何成功。
编辑
我是 运行 最新版本的 MongoDB 并且正在使用 mgo.v2 驱动程序。我想要实现的流程看起来像这样:
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.
您可以使用$elemMatch
collection.Find(bson.M{"gamecode": entry.GameCode},bson.M{"players": bson.M{"$elemMatch": bson.M{"playerid": playerid}}}).Limit(1).Count()