The code below returns me all data that are present in CollectionA but NOT in CollectionB . (Using the mainID
as reference).
return this.aggregate([
{
$lookup: {
from: 'CollectionB',
localField: 'mainId',
foreignField: 'mainId',
as: 'validd',
},
},
{
$match: {
'validd.mainId': { $exists: false },
},
},
]);
But now I need to add another filter . I also need to get data where the field createdAt
is greater than X days.
in other words: Records that have more than X days of life.
Tried using $gte
and $lte
inside $match
but didn’t work.
{
$match: {
'validd.createdAt': { $gte: moment.utc().add(-90, "days") },
},
},
Here is my database:
{
_id: 227dd33c5c51c79f63743da3
mainId: 5c306562-9c87-48dd-93ca-4a118be50490
createdAt: 2022-05-07T02:28:12.537+00:00
},
{
_id: f3ddd33c5c51c79f63743da3
mainId: 5c306562-9c87-48dd-93ca-4a118be50490
createdAt: 2022-05-10T02:28:12.537+00:00
},
{
_id: 227dd33c5c51c79f63743da3
mainId: 5c306562-9c87-48dd-93ca-4a118be50490
createdAt: 2022-01-01T02:28:12.537+00:00
}
To clarify. I need to return data if:
- row of collectionA does NOT exists in collectionB
- row of collectonA exists in collectionB BUT
createdAt
is greater than X days.
Also tried this, but didnt work. It returns data only when the first condition is meet.
return this.aggregate([
{
$lookup: {
from: 'CollectionB',
localField: 'mainId',
foreignField: 'mainId',
as: 'validd',
},
},
{
$match: {
$expr: {
$or: [
{
$eq: ["$validd", []]
},
{
$and: [
{
$lt: [ "validd.createdAt", moment.utc().add(-interval, "days").format('YYYY-MM-DD') ]
},
{
$ne: ["validd", null]
}
]
}
]
}
},
},
]);
Any helpp?