Search code examples
mongodbgomgo

Check for duplicates in an array of objects in Golang with MongoDB


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.


Solution

  • You can use $elemMatch

    collection.Find(bson.M{"gamecode": entry.GameCode},bson.M{"players": bson.M{"$elemMatch": bson.M{"playerid": playerid}}}).Limit(1).Count()