duanao2585 2018-10-31 02:51
浏览 238
已采纳

使用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.

  • 写回答

1条回答 默认 最新

  • doushi1912 2018-10-31 09:35
    关注

    You can use $elemMatch

    collection.Find(bson.M{"gamecode": entry.GameCode},bson.M{"players": bson.M{"$elemMatch": bson.M{"playerid": playerid}}}).Limit(1).Count()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 milvus查询出来的score怎么转换成0-1之间的相似性
  • ¥15 多ip服务器站群如何搭建l2tp服务器
  • ¥15 lvgl V9移植到linux开发板
  • ¥15 VB.net中在窗体中创建一个button控件来关闭窗体,但是提示错误,我该怎么办
  • ¥15 网上下载好的程序但是arduinoIDE编程报错,运行不了,哪里出错了,能具体给改一下吗
  • ¥15 Sharepoint JS开发 付费技术指导
  • ¥15 输入程序运行仿真后,烟雾值不实时检测,变成固定值
  • ¥20 数据排序,可选择排序方向
  • ¥15 修改一下代码,考虑进程到达时间不同的情况
  • ¥15 帮我看看这是个啥题,带解题过程和结果,条件如下FCF = 290471.33 g1 = 15% r = 8% g2 = 4% n = 5