So I have the following query, where I join 2 collections by a single field mainId
:
const interval = moment.utc().add(-5, "days"); // number of days may vary
return this.aggregate([
{
$lookup: {
from: 'collectionB',
localField: 'mainId',
foreignField: 'mainId',
as: 'validd',
},
},
{
$match: {
$or: [
{ "validd": [] },
{ "validd.createdAt": { $lt: new Date(interval) } }
]
}
},
]);
it works perfectly! But now I need to join those collection by another field named vid
.
I could make this join with two fields work like this:
return this.aggregate([
{
$lookup: {
from: "CollectionB",
let: {
mainIdField: "$mainId",
vidField: "$vid"
},
pipeline: [
{
$match: {
$expr: {
$and: [
{
$eq: ["$mainId", "$$mainIdField"]
},
{
$eq: [ "$vid", "$$vidField"]
}
]
}
}
}
],
as: "joined_results"
}
},
{
$unwind: { path: "$joined_results" }
}
])
But I can’t make both cases work toghether. I need to use both filters.
1 - Make the join with two fields;
2 - Apply the first example, where I only return values if:
2.1 - Itens from collectionA doesnt exists in collectionB
2.2 - row from collectionA exists in collectionB, but the field createdAt
is greather than X.
Is it possible?