1

我在 MongoDB 中有这个模式,团队和玩家之间的多对多关系:

团队:

{
    name: "Team1"
    players: ["1", "2"]
}
{
    name: "Team2"
    players: ["1"]
}

玩家:

{ id: "1", name: "Player1"}
{ id: "2", name:"Player2"}
{ id: "3", name:"Player3"}

我想查询所有不属于任何球队的球员。解决这个问题的最佳方法是什么?

4

1 回答 1

1

您需要分两步执行此操作。在外壳中:

// Find all the player ids that are part of teams
var ids = db.teams.distinct('players')

// Find all the players with ids not in that set.
db.players.find({id: {$nin: ids}})

返回:

{ "_id": ObjectId("5137947e0f26e0cc03fc3735"), "id": "3", "name": "Player3" }
于 2013-03-06T19:14:17.403 回答