【发布时间】:2013-02-20 23:40:51
【问题描述】:
我正在尝试对 games 的概念进行建模,其中 teams 和 players 在 MongoDB 中相互竞争。
我有两个集合:players 和 games。
games 中的文档是这样的。
{
"_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,
}
]
}
]
}
任务如下:给定一个玩家 ID,我想查找该玩家参与的所有游戏。
我尝试过的:
db.games.find( { "teams.players.player._id": "2" } )
但是,这不会返回任何内容。
顺便说一句,我正在使用具有以下架构的 Mongoose:
playerSchema = Schema
player: { type: Schema.ObjectId, ref: 'Player' }
score: { type: Number }
teamSchema = Schema
players: [ playerSchema ]
gameSchema = Schema
teams: [ teamSchema ]
使用以下 CoffeeScript 查询:
Game.find 'teams.players.player._id': playerId
不返回任何玩家 ID 的结果。
【问题讨论】:
-
如果你们认为架构可以设计得更好,我也很想得到一些指点!
-
您想要两个团队,还是两个以上?我可以为两个团队举一个不错的例子,但更多的团队有点乏味,并且涉及用于搜索目的的额外字段。
-
只有两个团队。谢谢!