Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB: How to find by subdocument ID?

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.

like image 736
Philipp Jardas Avatar asked Feb 17 '13 16:02

Philipp Jardas


1 Answers

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).

like image 178
Andy Glover Avatar answered Nov 15 '22 21:11

Andy Glover