Menu

Why swapping $match and $limit changes a MongoDB result
📰

Why swapping $match and $limit changes a MongoDB result

DEV Community: mongodb·WorkComposer Admin·1 day ago
#n5JcuneR
#devtomongodb#devto#dev#paid#sample
Reading 0:00
15s threshold

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.…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.