Please excuse if I made a newbie error in my code here.
I’m trying to merge the results of two queries (against different collections).
One is the Gedmatches
collection and this is the expected doc that should join with the 2nd collection:
the query:
db.gedmatches.find({ kit1: 'BkHXGDn4z', kit2: 'S1B52MvnVz' },{kit1:1,kit2:1})
the result:
{ "_id" : "w8WSXAjyvC8Ncxers", "kit1" : "BkHXGDn4z", "kit2" : "S1B52MvnVz" }
The other one is from the Kits
collection and this doc should come up as a result of the aggregation query (kitUser
is BkHXGDn4z
):
the match query in my code:
nameDoc.runningNo
is 1184
{ "_id" : "qfTzZ4TSaGuBhCuuK", "names" : [ 1183, 1184, 1185, 1186 ], "name" : "Sheridan Lugo", "kit23" : "S1B52MvnVz" }
Here’s my query, language is MeteorJS (nodeJS):
const pipeline = [
{
// get gedmatches with both kitUser on kit1/kit2
$match: { $or: [{ kit1: kitUser }, { kit2: kitUser }] },
},
{ $project: { kit1: 1, kit2: 1 } },
{
// let's create arrays for both kit1/kit2 and push kits
$group: {
_id: null,
kits1: { $push: '$kit1' },
kits2: { $push: '$kit2' },
},
}, {
// merge both arrays into 1
$project: { 'cousins': { '$setUnion': ['$kits1', '$kits2'] } },
}, {
// filter out kitUser from the array
$project: {
'cousins': {
$filter: {
'input': '$cousins',
'as': 'cousin',
'cond': { $ne: ['$$cousin', kitUser] },
},
},
},
}, {
// let's get docs from kits from our array
$lookup: {
'from': 'kits',
'localField': 'cousins',
'foreignField': 'kit23',
'as': 'cousins',
},
}, {
// unwind array so we have all as objects
$unwind: {
'path': '$cousins',
'preserveNullAndEmptyArrays': false,
},
}, {
// run our searchTerm using regexFindAll to get results that match it
$project: { 'kit23': '$cousins.kit23', 'match': { names: nameDoc.runningNo } },
}, {
// unwind our results as now we have a nested array, we want only 1
$unwind: { 'path': '$match', 'preserveNullAndEmptyArrays': false },
}, {
// get the kits docs that matched `Kits` query
$lookup: {
'from': 'kits',
'localField': 'kit23',
'foreignField': 'kit23',
'as': 'doc',
},
}, {
// unwind doc field, so we get the object and not an array with the object inside
$unwind: {
'path': '$doc',
'preserveNullAndEmptyArrays': false,
},
}, {
// only send back kit23 and doc on our object
$project: {
'_id': 0,
'kit23': '$kit23',
'doc': '$doc',
},
},
];
const gedMatchesArray = await GedmatchesRaw.aggregate(pipeline, { session: mongoSession }).toArray();
Result is an empty array
Any help is highly appreciated!