I am trying to model the concept of games
where teams
of players
compete against each other in MongoDB.
I have two collections: players
and games
.
This is how a document in games
looks like.
{
"_id": { "$oid": "1" },
"teams": [
{
"players": [
{
"player": { "$oid": "2" },
"score": 500,
},
{
"player": { "$oid": "3" },
"score": 550,
}
]
},
{
"players": [
{
"player": { "$oid": "4" },
"score": 500,
},
{
"player": { "$oid": "5" },
"score": 550,
}
]
}
]
}
Here's the task: given a player ID I want to find all games in which this player participated.
What I've tried:
db.games.find( { "teams.players.player._id": "2" } )
However, this does not return anything.
By the way, I'm using Mongoose with the following schema:
playerSchema = Schema
player: { type: Schema.ObjectId, ref: 'Player' }
score: { type: Number }
teamSchema = Schema
players: [ playerSchema ]
gameSchema = Schema
teams: [ teamSchema ]
with the following CoffeeScript query:
Game.find 'teams.players.player._id': playerId
which returns no results for any player ID.
In your document:
"players": [
{
"player": { "$oid": "4" },
"score": 500,
},
{
"player": { "$oid": "5" },
"score": 550,
}
]
The player
field in the embedded collection of players
is a BSON Id (i.e. it looks something like ObjectId("4e208e070347a90001000008")
), so I think you should structure your query like so:
db.games.find( { "teams.players.player": ObjectId("2") } )
Note, I've dropped the _id
-- provided that works in a mongo console, then I suspect the Coffee query will be similar (drop the _id
portion).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With