I want to be able to $lookup multiple collections and $match each collection.
I want to to match on player.player_name
.
And I want to match on player.team.team_name
.
I don't want to have the second match filter from the first match though, which is what I have right now.
I want the two lookups/matches to add to each other.
Report.aggregate(
[
{
"$lookup": {
from: Player.collection.name,
localField: "player",
foreignField: "_id",
as: "player"
}
},
{ "$match": { "player.player_name": { "$in": players } } },
{
"$lookup": {
from: Team.collection.name,
localField: "player.team",
foreignField: "_id",
as: "player.team"
}
},
{ "$match": { "player.team.team_name": { "$in": team } } }
]
)
For example, I have this data
{
player: {
player_name: 'Gerrit Cole'
team:
{
team_name: 'Astros'
}
}
},
{
player: {
player_name: 'Daniel Jones'
team:
{
team_name: 'Giants'
}
}
}
If I matched for player_name Gerrit Cole and team_name Giants, I need it to return both records.
EDIT:
This is a sample Player record:
{
_id: 5d3737f4d75f910eb785125f,
player_name: 'Yordan Alvarez',
player_position: 'Designated Hitter',
team: 5d30c5b423226e0ddc684b4e,
createdAt: 2019-07-23T16:38:12.801Z,
updatedAt: 2019-07-23T16:38:12.801Z,
__v: 0
}
This is a sample team record:
{
_id: 5d372e22d75f910eb78511c7,
team_name: 'Titans',
city_or_state: 'Tennessee',
league: 5d24c392d0a52545e8a345b1,
createdAt: 2019-07-23T15:56:18.304Z,
updatedAt: 2019-07-23T15:56:18.304Z,
__v: 0
}
I could not find anything related to Reports collection which you have used in your query example. Based on the 2 sample records for team
and player
collection, following query should work. You do not need to use 2 lookup
, rather need one unwind
operation.
db.player.aggregate([{
"$lookup": {
from: "team",
localField: "team",
foreignField: "_id",
as: "team"
}
}, {
$unwind: "$team"
}, {
$match: {
$or: [{
"player_name": {
"$in": players
}
},
{
"team.team_name": {
"$in": teams
}
}
]
}
}])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.