I have two collections and I need to group documents from both using a single query using $lookup and $group.
Here is my db data and the expected output:
currentBills table
const currentBills = [
{
memberId: 1,
name: 'Mark',
status: 'paid'
},
{
memberId: 2,
name: 'Steve',
status: 'unpaid'
},
{
memberId: 3,
name: 'William',
status: 'paid'
}
];
pastBills table
const pastBills = [
{
memberId: 5,
name: 'Joe',
status: 'paid'
},
{
memberId: 8,
name: 'Carlos',
status: 'paid'
},
{
memberId: 25,
name: 'ben',
status: 'unpaid'
}
];
expected output
const result = {
CurrentBill: {
paid: [
{
memberId: 1,
name: 'Mark',
status: 'paid'
},
{
memberId: 3,
name: 'William',
status: 'paid'
}
],
unpaid: [
{
memberId: 2,
name: 'Steve',
status: 'unpaid'
}
]
},
pastBill: {
paid: [
{
memberId: 5,
name: 'Joe',
status: 'paid'
},
{
memberId: 8,
name: 'Carlos',
status: 'paid'
}
],
unpaid: [
{
memberId: 25,
name: 'ben',
status: 'unpaid'
}
]
}
};
my query
db.getCollection('currentBills').aggregate([
{
$lookup:
{
from: "pastBills",
localField: "memberId",
foreignField: "memberId",
as: "bill"
}
},{
$unwind : "$bill"
},
{
$group : {
_id : "$status"
}
}
])
How to group each collections by the status and return a single result? Is this possible using a single aggregation query?
Thanks in advance!