How can i sort data coming from multiple tables joined by lookup

Hi @Naila_Nosheen and welcome in the MongoDB Community :muscle: !

You have the wrong way to do it and the right way to do it. :wink:
The wrong way would be to use $unwind to break down the array (I think topics_mcqs_info here) and rebuild the question array with a $group using $push and with a $sort before that group stage to sort the docs in the order you want.

This would work but add a lot of useless processing (=breaking down the array and rebuilding it).

The right solution is to use the other format of $lookup, the one that is using a subpipeline, so you can actually sort the docs directly in there and build the array of questions already sorted.

You pipeline will probably look like this:

db.orders.aggregate( [
   {
      $lookup: {
         from: "mcqs",
         localField: "_id",
         foreignField: "topicId",
         pipeline: [ {
            $sort: {
               sequenceNumber: 1
            }
         } ],
         as: "topics_mcqs_info"
      }
   }, 
   { the other similar lookup stage here }
] )

I think this should work. Please provide a few sample docs if you can’t figure it out so I can test it on my side.

Cheers,
Maxime.