EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login

MongoDB group by

By Priya PedamkarPriya Pedamkar

Home » Data Science » Data Science Tutorials » MongoDB Tutorial » MongoDB group by

MongoDB group by

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:

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

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.

Popular Course in this category
MongoDB Training Program (4 Courses, 2 Projects)4 Online Courses | 2 Hands-on Projects | 22+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,463 ratings)
Course Price

View Course

Related Courses
Oracle Training (14 Courses, 8+ Projects)All in One Data Science Bundle (360+ Courses, 50+ projects)SQL Training Program (7 Courses, 8+ Projects)Oracle DBA Database Management System Training (2 Courses)MS SQL Training (13 Courses, 11+ Projects)
  • $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:

MongoDB group by 1

Below is the documents of emp_test collection.

Code:

db.emp_test.find()

Output:

MongoDB group by 2

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:

using $

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:

two fields

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:

Calculate number of emp_id

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 –

  1. MongoDB Timestamp
  2. MongoDB Date Query
  3. MongoDB Skip()
  4. MongoDB Relationships

All in One Data Science Bundle (360+ Courses, 50+ projects)

360+ Online Courses

50+ projects

1500+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
MongoDB Tutorial
  • Commands
    • MongoDB Limit()
    • MongoDB count
    • MongoDB Aggregate
    • MongoDB Distinct
    • MongoDB Unique
    • MongoDB find
    • MongoDB insert
    • MongoDB Delete
    • MongoDB Update
    • Lookup in MongoDB
    • order by in MongoDB
    • MongoDB $regex
    • MongoDB $elemMatch
    • MongoDB ObjectId()
    • MongoDB Skip()
    • MongoDB Date Query
    • MongoDB Timestamp
    • MongoDB sort()
    • MongoDB group by
    • MongoDB Join
  • Basics
    • What is MongoDB
    • How To Install MongoDB
    • MongoDB Tools
    • MongoDB GUI Tools
    • MongoDB Versions
    • MongoDB Commands
    • Advantages of MongoDB
    • MongoDB Features
    • Is MongoDB NoSQL
    • Is MongoDB Open Source
    • Build Web Applications using MongoDB
    • MongoDB vs Elasticsearch
    • MariaDB vs MongoDB
    • Firebase vs MongoDB
  • Advanced
    • MongoDB Array
    • PostgreSQL ARRAY_AGG()
    • Indexes in MongoDB
    • MongoDB create Index
    • MongoDB Collection
    • MongoDB List Collections
    • MongoDB Capped Collections
    • MongoDB Auto Increment
    • MongoDB Projection
    • Replication in MongoDB
    • Mongo DB Create Database
    • MongoDB Compass
    • MongoDB Users
    • MongoDB Authentication
    • MongoDB GridFS
    • MongoDB Relationships
    • MongoDB Monitoring
    • Backup in MongoDB
    • MongoDB Sharding
    • MongoDB Java Drivers
    • MongoDB Import
    • Mongo Database Interview Questions

Related Courses

MongoDB Certification Course

Oracle Certification Course

All in One Data Science Course

SQL Training Course

Oracle DBA Course

MS SQL Certification Course

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - MongoDB Certification Course Learn More