After introduction of group stage let's combine $match and $group stages. So
direct jump to example using our person collection.
Now let's switch both stages means first we will see group stage and after that match stage so let's try below example in ROBO 3T.
db.getCollection("person").aggregate([ {$match:{country:"China"}}, // stage 1 {$group:{_id:{age:"$age", gender:"$gender",}}} // stage 2 ]);In above example first we use match stage where we find all document whose country is china and next group stage and finally we will get documents with _id set to have embedded document with two filed age and gender, so remember all document in person collection go to match stage first we will filter and find only document whose country is china and then resulting document will go to group stage and group will produce brand new documents that will contain all possible combination of age and gender of the document came out from match stage. Result shown below in image.
Now let's switch both stages means first we will see group stage and after that match stage so let's try below example in ROBO 3T.
db.getCollection("person").aggregate([ {$group:{_id:{age:"$age", gender:"$gender",}}}, // stage 1 {$match:{country:"China"}} // stage 2 ]);Above example's result will be empty because order of aggregation stage is wrong. In above query first stage output will be _id with embedded document of all possible combination of age and gender after that in second stage we are trying to filter document whose country is China but in this example first stage only contain _id fields as output so when it pass to second stage and try to match with country we get empty result. So in aggregation, order of aggregation execution is also important to get expected result.
Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .