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

Hi @Naila_Nosheen,

Then I would remove the sorts from the lookups (as they would be redundant) and I would add the following at the end of your pipeline:

[
  {
    '$addFields': {
      'all': {
        '$sortArray': {
          'input': {
            '$concatArrays': [
              '$topics_mcqs_info', '$topics_trueFalse_info', '$topics_openEnded_info'
            ]
          }, 
          'sortBy': {
            'sequence': 1
          }
        }
      }
    }
  }, {
    '$project': {
      'topics_mcqs_info': 0, 
      'topics_trueFalse_info': 0, 
      'topics_openEnded_info': 0
    }
  }
]

Note that $sortArray is new in 5.2.

If 5.2 isn’t yet possible for you, then you have an alternative but it’s a little bit unpleasant. Read this for more details.

Cheers,
Maxime.

3 Likes