One output given 3 inputs for 3 different collections

I currently have 3 mongodb collections that are in the following format:

collection = {
     "Link":link,
     "theAssociatedList":myList
}

Here is an example query where I provide a link and retrieve the associated list:

myquery = { "Link1": uri }
myd = firstCollection.find(myquery)
theOutputList= myd[0]["theAssociatedList"]

Where theOutputList is equal to [A1,A2,…,A3].

After querying all three collections, I receive lists [A1,A2,...,A3], [B1,B2,...,B3], and [C1,C2,...,C3] as output, given inputs, Link1, Link2, and Link3. How can I receive [A1,B1,C1,A2,B2,C2,A3,B3,C3,...] in the same step as the query to save runtime, or some other fast solution?

Hi @lilg263,

Welcome to MongoDB Community.

So this is possible to achieve via a complex aggregation.

However I believe from coding perspective it is better to do it on the client side after doing 3 queries using your programming langugue.

If you still need the aggregation see the following:

myquery = { "Link1": uri }
firstCollection.aggregate([{$match: {
  Link : "http://myexample.com"
}},
// Get second collections
 {$lookup: {
  from: 'secondCollection',
  pipeline : [{"$match" : {
  Link : "http://myexample.com"
}}],
  as: 'secondCollection'
}}, {$lookup: {
  from: 'thirdCollection',
  pipeline : [{"$match" : {
  Link : "http://myexample.com"
}}, {$project : {theAssociatedList:1}}],
  as: 'thirdCollection'
}},
// Create 3 arrays
 {$project: {
  Link : 1,
  theAssociatedList1 : "$theAssociatedList",
  theAssociatedList2 : { $first : "$secondCollection.theAssociatedList" },
  theAssociatedList3 : { $first : "$thirdCollection.theAssociatedList" }
}},

// Zip them in the needed order 
{$project: {
  Link : 1,
  theAssociatedList: {
   $zip : {
     inputs : ["$theAssociatedList1", "$theAssociatedList2","$theAssociatedList3"],
     useLongestLength : true
   }
  }
}}, 
// Make one array of them
{$project: {
  Link : 1,
  theAssociatedList : {$concatArrays: [ 
        { $arrayElemAt : ["$theAssociatedList",0] }, 
        {$arrayElemAt : ["$theAssociatedList",1]}, 
        {$arrayElemAt : ["$theAssociatedList",2]}]
  }
}}])

This will output the following in my tests:

[ { _id: 
     { _bsontype: 'ObjectID',
       id: <Buffer 60 22 5a c4 7d 5d d6 62 64 6d e6 42> },
    Link: 'http://myexample.com',
    theAssociatedList: [ 'A1', 'B1', 'C1', 'A2', 'B2', 'C2', 'A3', 'B3', 'C3' ] } ]

Thanks,
Pavel