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 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?