Updated March 4, 2023
Introduction to MongoDB group by
MongoDB group by is used to group data from the collection, we can achieve group by clause using aggregate function and group method in MongoDB. While using aggregate function with group by clause query operations is faster as normal query, basically aggregate function is used in multiple condition. We can group by single as well as multiple field from the collection, we can use $group operator in MongoDB to group fields from the collection and returns the new document as result. We are using $avg, $sum, $max, $min, $push, $last, $first and $addToSet operator with group by in MongoDB.
Syntax of MongoDB group by
Given below is the syntax:
1. Group by using $group aggregation
{ $group (Aggregation is used to define group by): { _id: <expression>, <field1>: { <accumulator1> : <expression1> }, <accumulator2> : <expression2>, <accumulator3> : <expression3> } }...<accumulatorN> : <expressionN> } } }
2. Group by using group method
db.name_of_collection.group ({key or field, reduce (aggregation function), initial (initialize the result of aggregation) [, keyf (it is alternative of the key field)] [, condition] [, finalize] })
Parameters
Below is the parameter description syntax of group by in MongoDB:
- $group: This is defined as using accumulator and the expression we have retrieving the grouped data from the collection. The output of this aggregation is _id field which contains the group by key of distinct records. Group by is not order the result documents.
- _id: This field is mandatory while using aggregation with group operator. We can specify the id value with null value for calculating the accumulated value from the all input values.
- Expression: This is defined as expression which we have using with the group by in MongoDB. Expression with group by is accepting the valid expression.
- Accumulator: We are using the accumulator operator with group operator in MongoDB. By using accumulator with the expression is accepting the valid expression.While using group by in MongoDB it is must to be use any one accumulator by using group by.
- Field: This is defined as field name which we are using with group by in MongoDB.
How group by works in MongoDB?
We are using group method and aggregation operation to use group by in MongoDB.
We are using below operator to group by multiple fields.
- $sum: This operator is used to return the sum of all the numeric fields using $group operator. This operator ignores the non-numeric values from the collections.
- $addToSet: This operator is used to return the each group array unique expression value using $group operator. The order of this operator array elements is undefined.
- $avg: This operator is used to return the average of all the numeric fields using $group operator. This operator ignores the non-numeric values from the collections.
- $first: This operator is used to return the each group first document using $group operator.
- $last: This operator is used to return the each group first document using $group operator.
- $max: This operator is used to return the highest value from each group.
- $min: This operator is used to return the lowest value from each group.
- $mergeObjects: This operator is used to return the documents which was combined by using input document.
- $push: This operator is used to return the expression of array values from each group.
We are also using the group method to group the documents in MongoDB. Using the group method we are grouping by two or multiple field in MongoDB. Group method will accept the single document from the collection. Basically group method is similar to group by clause which was used in other SQL databases.
Group method uses following parameter are as follows:
- Initial
- Key
- Reduce
- Cond
- Finalize
- Keyf
The value of initial parameter will initialize field which represents the document from group.
Examples of MongoDB group by
Given below are the examples mentioned:
We are using group_by and emp_test collection to describe example of group by in MongoDB.
Below is the documents of group_by collection.
Code:
db.group_by.find()
Output:
Below is the documents of emp_test collection.
Code:
db.emp_test.find()
Output:
Example #1
Group by using $group aggregation.
- Below example shows that group by using $group aggregation.
- We are using _id field in $group aggregation.
Code:
db.group_by.aggregate( [
{
$group: {
_id: "_id",
count: { $sum: 1 }
}
}
] )
Output:
Example #2
Group by two fields by using group method.
- Below example shows that group by two fields using group method.
- In below example we have used key field as emp_id and cond as emp_id.
Code:
db.emp_test.group(
{
key: { "emp_id": 1, "gross.da": 1 },
cond: { "emp_id": { $lt: 101 } },
reduce: function ( curr, result ) { },
initial: { }
}
);
Output:
Example #3
Calculate number of emp_id using group method.
- Below example shows that calculate number of emp_id using group method.
- In below example we have used key as emp_id from the emp_test table.
Code:
db.emp_test.group({
key:{emp_id:1},
cond:{},
reduce:function(current, result)
{
result.total += 1;
},
initial:{total:0}
})
Output:
Conclusion
We can use single as well as multiple fields with aggregate function to group by the documents and fetch result from collection. Group method is used to group the documents from the collection. We are using avg, sum, max and min operator with group by in MongoDB.
Recommended Articles
This is a guide to MongoDB group by. Here we discuss how group by works in MongoDB along with examples respectively. You may also have a look at the following articles to learn more –