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 网络科学导论,网络控制
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)