我有以下两个收藏,我希望能够加入他们,并输出玩家A和玩家B玩的总游戏数量。
profiles collection
[
{
name: 'A'
player_id: 1
},
{
name: 'B'
player_id: 2
}
{
name: 'C'
player_id: 3
}
]
games collection
[
{
game_id: 1
player_id: 1
},
{
name: 2
player_id: 2
},
{
game_id: 3
player_id: 1
},
{
name: 4
player_id: 2
}
{
name: 5
player_id: 3
}
]
现在的目标是输出给我A和B而不是C的玩家总数,而我却获得了他们的名字而不是ID。因此,下面的SQL语句:
SELECT * FROM (results for A) UNION (results for B);
所以我正在使用查找来组合这样的集合:
db.games.aggregate([
{
'$lookup':
{
from: "profiles",
localField: "player_id",
foreignField: "player_id",
as: "player"
}
},
{
"$addFields": {
"player": {
"$filter": {
"input": "$player",
"as": "p",
"cond": {
"$eq": [ "$$p.name", "A" ]
}
}
}
}
},
])
当我只是查找时,它会使用player_id创建一个“玩家”字段,其中包含该玩家的信息,但是当我添加“ addField”时,玩家会空着。
答案 0 :(得分:0)
要查找玩家A和B玩过的游戏总数,请尝试以下操作:
db.games.aggregate([
{
'$lookup':
{
from: "profile",
localField: "player_id",
foreignField: "player_id",
as: "player"
}
},
{
$match: {
'player.name': { $in: ['A','B']}
}
},
{
$group: {
_id: null,
total: { $sum: 1 }
}
}
])