I'm trying to build a game server and we are using MongoDb as the database.
We have a collection Games that has models like this:
{
"_id" : ObjectId("5d1b345b8ea742034db76431"),
"Users" : [
{
"_id" : "0e76bd95-a7c2-4e15-b2bc-4cdf741fe9aa",
"UserName" : "l98lNhLHPh",
"Cards" : [
249
]
},
{
"_id" : "6ffec61d-45cc-46fa-a1f0-2a3e0a03fef6",
"UserName" : "Vun12sWp4W",
"Cards" : [
234
]
}
],
"CreatedAt" : ISODate("2019-07-02T15:09:23.303+04:30"),
"UpdatedAt" : ISODate("2019-07-02T15:09:23.674+04:30"),
"IsFinished" : false
}
We can easily query users that participated in a game, but what if we need to know the games that a special user had played before?
We reached two solutions but we don't know which one is better.
First, query using nested field with an index on Users.UserName:
db.games.find({"Users.UserName":"Amin"})
Second, create a new collection that holds the User and Games data.
// collection: UserGames
{
"_id" : ObjectId("5d1b35c58ea742034db79fea"),
"UserId" : "6ffec61d-45cc-46fa-a1f0-2a3e0a03fef6",
"GameId" : ObjectId("5d1b35c58ea742034db79fe9")
}
and join Games and UserGames collections to find the which user played which games.
I came from a Relational database mindset and I don't know which approach should I take?