Hi,
Let’s say I have these collections
// collection name: Collection1
{_id: 1, name: 'name1'}
{_id: 2, name: 'name2'}
{_id: 3, name: 'name3'}
// collection name: Collection2
{
_id: 9,
my_array: [
{
value: 5,
collection1_id: 2,
collection1_ids: [1]
},
{
value: 7,
collection1_id: 3,
collection1_ids: [2,3]
}
]
}
I want to output Collection2
with join to Collection1
via collection1_ids
and the output should look like this
{
_id: 9,
my_array: [
{
value: 5,
collection1_id: 2,
collection1_name: 'name2',
collection1_array: [
{_id: 1, name: 'name1'}
]
},
{
value: 7,
collection1_id: 3,
collection1_name: 'name3',
collection1_array: [
{_id: 2, name: 'name2'},
{_id: 3, name: 'name3'}
]
}
]
}
I tried to use pipeline aggregation + map + lookup equality match without success.
[
$lookup: {
from: 'Collection1',
localField: 'my_array.collection1_id',
foreignField: '_id',
as: 'AsCollection1'
},
$lookup: {
from: 'Collection1',
localField: 'my_array.collection1_ids',
foreignField: '_id',
as: 'AsCollection1s'
},
$project: {
_id: '$_id',
my_array: {
$map: {
input: '$AsCollection1',
as: 'collection1',
in: {
$mergeObjects: [
{
collection1_id: '$$collection1._id',
collection1_name: '$$collection1.name',
},
{
$arrayElemAt: [
{
$map: {
input: '$my_array',
as: 'my_array',
in: {
value: '$$my_array.value',
collection1_array: {
$map: {
input: '$AsCollection1s',
as: 'collection1s',
in: {
_id: '$$collection1s._id',
name: '$$collection1s.name'
}
}
},
}
}
},
{$indexOfArray: ['$my_array._id', '$$collection1._id']},
],
}
]
}
}
}
}
]
How can I achieve this?
Thank you,