Lets imagine I have:
CollectionA
name: “first”
mainId: a2345e87
email: “abc@gmail.com”name: “second”
mainId: a2345e87
email: “def@gmail.com”name: “third”
mainId: c2345e87
email: “ghi@gmail.com”name: “fourth”
mainId: a2345e87
email: “abc@gmail.com”
We can notice that mainId=a2345e87
repeats 3 times. Rows first
, second
and fourth
.
But only rows first
and fourth
have same emails.
How to retrieve only one row when this happens. (mainId + email are the same) ?
Is like a mysql GROUP BY two fields. Tried to do this using the documentation but I failed.
It returned me a single field (the one I grouped by, or demands me to use an accumulator).
I Want all fields, just want to pick a single row when two or more fields are the same.
The result I want:
name: “first”
mainId: a2345e87
email: “abc@gmail.com”name: “second”
mainId: a2345e87
email: “def@gmail.com”name: “third”
mainId: c2345e87
email: “ghi@gmail.com”
I need to plug this solution inside the aggregation I already have:
return this.aggregate([
{
$lookup: {
from: 'collectionB',
localField: 'mainId',
foreignField: 'mainId',
as: 'allowed',
},
},
{
$match: {
{
$or: [
{ 'allowed': [] }, // if collectionA.mainId doesn't exist inside collectionB
{ 'allowed.expires': { $lt: new Date(interval) } }, // if CollectionA.mainId exists inside collectionB BUT the field expires is longer than a certain interval
],
},
},
},
]);