In Last tutorial we have seen $match stage now we will see how $group stage works so let's begin.
$group stage is very important stage of aggregation because it is use often in aggregation query. Groups documents by some specified expression and outputs to the next stage a document for each distinct grouping. Let's look in to syntax.
Lets look in to another example
Above was just introduction of $group stage. We will see more in detail and more example and combination of $match and $group stage in next tutorials.
$group stage is very important stage of aggregation because it is use often in aggregation query. Groups documents by some specified expression and outputs to the next stage a document for each distinct grouping. Let's look in to syntax.
$group Aggregation Stages Syntax
{ $group: { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, ... } }The _id field is mandatory other are optional, we can specify an _id value of null, or any other constant value. Now let's see how it's works, before group stage we have set of documents, those document has certain fields and if we want to group those document by certain fields name, then we should use these fields name as expression on the right side of _id as key value pair and as a result we will get documents with one fields _id and values which will depend on field we use in expression. It may sound difficult but when we start working with it will get easy let's look in to example.
db.getCollection("person").aggregate([{$group:{_id:"$age"}}]);In above example we grouping documents by age fields and finding distinct values of age fields and then producing new set of document and each of new document have just one field name _id. Values will be distinct values of age fields of input documents e.g. shown in below image.
Lets look in to another example
db.getCollection("person").aggregate([{$group:{_id:{age:"$age",gender:"$gender"}}}]);Second example we grouping data with two fields age and gender, so we will find unique pair document of age and gender and output as separate document. each output have nested document as values. These nested documents will have two fields age and gender. Below image is output of second query.
Above was just introduction of $group stage. We will see more in detail and more example and combination of $match and $group stage in next tutorials.
Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .
0 comments:
Post a Comment