'Is there a way to perform subquery on MongoDB using collection.aggregate() and PHP Driver?

I am migrating a MySQL table which has 50 million+ rows and 40 columns to a MongoDB database. This table data is shown on a html table and every column is searchable and sortable. To get a better performance on MySQL queries I make a subselect from this table filtering by a column named company_id and limiting it to 50k rows and ordering by id and date to get the last 50k rows that belongs to that company, and then from this subselect I perform the other filtering and ordering logics sent by frontend. Basically this is how the MySQL Query looks like:

SELECT *
  FROM (
            SELECT field1, field2, field3, field4 -- other fields
              FROM myTable
             WHERE company_id = 50
             ORDER BY id DESC, dateField desc
             LIMIT 50000
         ) AS tb
 WHERE tb.field1 = 'A filter'
   AND tb.field2 = 'Another filter'
 -- more and more filters
 ORDER BY tb.FIELD3

There is any way to do something like that on a MongoDb table using db.collection.aggregate() and Mongo PHP Driver?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source