An aggregation expected to return three paid orders can return just one if the limit runs before the filter. To see what happened, inspect the documents entering and leaving each stage.
We build KeplerGrid, a desktop MongoDB client. To reproduce this example, choose Load sample data , open orders , then select Aggregation → JSON . The built-in sample runs without connecting to a database.
[ { "$sort" : { "reference" : 1 } } , { "$match" : { "status" : "paid" } } , { "$limit" : 3 } ]
Enter fullscreen mode
Exit fullscreen mode
Click Run pipeline . You should see three paid orders. Keep the sort first and swap the last two stages.
[ { "$sort" : { "reference" : 1 } } , { "$limit" : 3 } , { "$match" : { "status" : "paid" } } ]
Enter fullscreen mode
Exit fullscreen mode
Run it again, switch to Stages , and select $match . Its input now has three orders, and its output has just one paid order.…