Inner joins 2 tables in mongoose
You just need to correct your second lookup with genre collection, i have added 2 approaches you can use anyone,
1) Using your approach:
localField
pass previous lookup result'smovieGenres.genreId
foreignField
passid
of genre collection
{ $lookup: { from: Genre.collection.name, localField: "movieGenres.genreId", foreignField: "id", as: "genreNames" } }
if you want to filter the genreNames
names from above lookup by name
,
$filter
to iterate loop ofgenreNames
array and filter byname: Action
{ $addFields: { genreNames: { $filter: { input: "$genreNames", cond: { $eq: ["$$this.name", "Action"] } } } } }
Your final query would be,
{ $lookup: { from: MovieGenre.collection.name, localField: "id", foreignField: "movieId", as: "movieGenres" } }, { $lookup: { from: Genre.collection.name, localField: "movieGenres.genreId", foreignField: "id", as: "genreNames" } }, { $match: { "genreNames.name": "Action" } }, { $addFields: { genreNames: { $filter: { input: "$genreNames", cond: { $eq: ["$$this.name", "Action"] } } } } }
2) Using lookup with pipeline approach:
The alternate way to do this using lookup with pipeline,
let
to passmovieGenres.genreId
from above lookup$match
to matchgenreId
using$expr
expression match andname
field and combine conditions using$and
operations
{ $lookup: { from: MovieGenre.collection.name, localField: "id", foreignField: "movieId", as: "movieGenres" } }, { $lookup: { from: Genre.collection.name, let: { genreIds: "$movieGenres.genreId" }, pipeline: [ { $match: { $and: [ { $expr: { $in: ["$id", "$$genreIds"] } }, { name: "Action" } ] } } ], as: "genreNames" } }