Mongo:查询对象与另一个不相关(多对多)

时间:2013-03-06 17:57:58

标签: mongodb many-to-many

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

小组:

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

播放器:

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

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

1 个答案:

答案 0 :(得分:1)

您需要分两步完成。在shell中:

// 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" }