Hi @MWD_Wajih_N_A ,
Ok this is a pretty unnatural requirement for a join and you should consider a redesign of the schema to better support a more efficient join across documents like keeping some embedded indexes to join the collection.
However, it is possible to build a pretty complex aggregation which is probably not very efficient but it can join documents of this type by this condition:
// Save the root object for further grouping
[{$addFields: {
root: "$$ROOT"
}},
// Unwind the arrays and add indexes
{$unwind: {
path: '$Array',
includeArrayIndex: 'idx'
}},
// Lookup using an internal pipeline to equal idx and parent Array value
{$lookup: {
from: 'collB',
let : { "parent" : "$Array" , idx : "$idx"},
pipeline : [{$addFields: {
root: "$$ROOT"
}},{$unwind : {
path: '$Array',
includeArrayIndex: 'idx'
}},{$match : {$expr: { $and : [ { $eq : [ "$idx", "$$idx" ] }, {$eq : [ "$Array", "$$parent" ]}]}}}],
as : "collB"
}},
// Filter garbage unmatched elements
{$match: {
$expr : {$gt : [ {$size : "$collB"}, 0]}
}},
// Rebuild the objects to have the matched documents as a lookedup document
{$replaceRoot: {
newRoot: { $mergeObjects : ["$root", {"collB" : "$collB.root" }] }
}}]
Result:
db.collA.find()
{ _id: ObjectId("61025cc6b818e0b49461d57d"),
id: 1,
Array: [ 1, 2, 2, 4, 5 ] }
db.collB.find()
{ _id: ObjectId("61025cf4b818e0b49461d57e"),
id: 3,
Array: [ 5, 3, 2, 7, 9 ] }
db.collA.aggregate([{
$addFields: {
root: "$$ROOT"
}
}, {
$unwind: {
path: '$Array',
includeArrayIndex: 'idx'
}
}, {
$lookup: {
from: 'collB',
let: {
"parent": "$Array",
idx: "$idx"
},
pipeline: [{
$addFields: {
root: "$$ROOT"
}
}, {
$unwind: {
path: '$Array',
includeArrayIndex: 'idx'
}
}, {
$match: {
$expr: {
$and: [{
$eq: ["$idx", "$$idx"]
}, {
$eq: ["$Array", "$$parent"]
}]
}
}
}],
as: "collB"
}
}, {
$match: {
$expr: {
$gt: [{
$size: "$collB"
}, 0]
}
}
}, {
$replaceRoot: {
newRoot: {
$mergeObjects: ["$root", {
"collB": "$collB.root"
}]
}
}
}])
{ _id: ObjectId("61025cc6b818e0b49461d57d"),
id: 1,
Array: [ 1, 2, 2, 4, 5 ],
collB:
[ { _id: ObjectId("61025cf4b818e0b49461d57e"),
id: 3,
Array: [ 5, 3, 2, 7, 9 ] } ] }
Hope this helps.
Thanks
Pavel